Académique Documents
Professionnel Documents
Culture Documents
C++ Programming
Takamitsu Kawai
kawai@csee.wvu.edu
304-293-0405 x4212 G11 CERC building WV Virtual Environments Lab West Virginia University
What is C++ ?
C++ was designed at AT&T Bell Labs by Bjarne Stroustrup in the early 80s
C with class Translator from C++ to C (called cfront) existed
C++...
supports data abstraction supports object-oriented programming supports generic programming is a better C
C++...
supports object-oriented programming Inheritance (class), polymorphism (virtual functions, operator overloading) supports data abstraction Class supports generic programming Parameterized types (templates)
int main() // program starts here { cout << Hello, world ! << endl;
// same as // cout << Hello, world !\n; // return to the OS
return 0;
- Integers Type Size(bytes) Type Size char 1 int 4 short 2 long long 8 bool 4 signed/unsigned: signed char (-128 ~ 127) unsigned char (0 ~ 255) - Floating point numbers Type Size(bytes) float 4 double 8
. -> [] () () ++ --
member selection member selection subscripting function call value construction post increment post decrement
size of object size of type pre increment pre decrement complement not unary minus unary plus
& lvalue * expr new type delete pointer delete[] pointer (type) expr
object.*pointer_to_member pointer ->*pointer_to_member expr * expr expr / expr expr % expr expr + expr expr - expr
expr << expr expr >> expr
+ << >>
add subtract
shift left shift right
L/R L/R
L/R L/R
:: is the highest priority , is the lowest priority L/R: left associative R/L: right associative
Operating System
$status
(shell variable)
Using streams
stream: a general name of a flow of data cin, cout : standard input/output (cerr also exists.) cf. stdin, stdout, stderr
#include <iostream> using namespace std; int main() { int a, b; cout << "Input two integers:"; cin >> a >> b; cout << a << " + " << b << " = " << a + b << '\n'; return 0; }
Note: cout, cin, cerr are NOT keywords. They are defined in iostream.
Manipulators
#include <iostream> #include <iomanip> using namespace std; int main() { int i = 123; cout << "Octal : " << oct << i << endl << "Decimal : " << dec << i << endl << "Hexadecimal: " << hex << i << endl; float f = 1.23456; cout << "Precision=1: " << setprecision(1) << f << endl << "Precision=2: " << setprecision(2) << f << endl << "Pricision=3: " << setprecision(3) << f << endl << "Width=4 Precision=1: " << setw(4) << setprecision(1) << f << endl << "Width=5 Precision=2: " << setw(5) << setprecision(2) << f << endl << "Width=6 Precision=3: << setw(6) << setprecision(3) << f << endl; return 0; }