CIS-255 Home: http://www.c-jump.com/bcc/c255c/c255syllabus.htm
// My first C++ program
#include <iostream>
int main()
{
std::cout << "Hello, World" << std::endl;
return 0;
}
Control constructs:
function calls
for while if-else switch
etc.
Native types
int, float, double, char, void, bool
Arrays and pointers
C++ dynamic allocation syntax
#include <iostream> std::cout, std::cin, std::cerr // stdout, stdin, and stderr in C std::endl
The << and >> operators
Keyword enum
Examples:
enum Suit { CLUB, DIAMOND, HEART, SPADE };
Suit s; // enum keyword here not required
s = CLUB; // of course
s = (Suit) 1; // Ok, not recommended
s = 1; // ERROR
switch ( s ) { //...
enum PrintFlags {
COLOR = 1,
LANDSCAPE = 2,
TWOSIDE = 4
};
Keywords struct and class
struct Point { int x; int y; };
-or-
class Point {
public:
int x;
int y;
};
Point p1; // Note: struct keyword not needed
p1.x = 9;
p1.x = 2;
C supports structs. In C++ structs and classes can also have functions.
#include <iostream>
#include <string>
using std::string;
int main()
{
string s1 = "This is a string";
std::cout
<< "There are "
<< s1.length()
<< " chars in "
<< s1
<< std::endl
;
return 0;
}
// main.cpp
class Point {
public:
// member variables
int x;
int y;
// member functions
void adjust( int xx, int yy )
{
x += xx;
y += yy;
}
}; // don't forget this semicolon!
int main()
{
// Create object
Point pt;
// access to member variables
pt.x = 5;
pt.y = 4;
pt.adjust( 1, 1 ); // member function call
return 0;
}
First, try being a client:
use existing objects where possible.
Second, design your own classes,
but keep in mind the client perspective.
// comments from there to end of line
/*
multi-line
comment
*/
Avoid mixing comments, since neither type respects the other:
// this --> /* is not effective
so this becomes an error */
/* this --> // is not effective */ so this is an error
Some compilers may give you a warning when comments are mixed.