#include <stdlib>
#include <iostream>
int main()
{ int x, y;
std::cout << "Please enter two numbers: ";
std::cin >> x >> y; // input stream
int sum = x + y;
std::cout << "Their sum is " << sum << std::endl;
return EXIT_SUCCESS;
}
bool char short int long float double enum |
boolean character integer integer long integer single-precision floating point double-precision floating point enumeration |
true, false писмен знак, символ 'A' къс цял цял дълъг цял единична точност плаваща запетая двойна точност плаваща запетая изброяване - множество от отделни стойности |
Указатели (pointers)enum Color { RED, GREEN, BLUE }; // default values are 0, 1, 2
enum Week { MONDAY = 1, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY};
// values are 1, 2, 3, .., 7
enum Mood { HAPPY = 3, SAD = 1, ANXIOUS = 4, SLEEPY = 2 };
Color skyColor = BLUE;
Mood myMood = SLEEPY;
Week day = TUESDAY;
char ch = 'Q';
char* p = &ch; // p holds the address of ch
cout << *p; // outputs the character 'Q'
ch = 'Z'; // ch now holds 'Z'
cout << *p; // outputs the character 'Z'
C++ не поддържа проверка за излизане на индексите извън границите на масива [common programming error]!double f[3]; // array of 3 doubles f[0], f[1], f[2]
double* p[10]; // array of 10 double pointers p[0]..p[9]
f[2] = 2.5;
p[4] = &f[2]; // p[4] points to f[2]
cout << *p[4]; // outputs 2.5
int a[] = { 10, 11, 12, 13 }; // initialization
int b[20] = { 0 }; // initialize all elements with value 0
enum MealType { NO_PREF, REGULAR, LOW_FAT, VEGETARIAN }; |
|
Passenger *p; |
Оставяне на недостъпни обекти в динамичната памет се нарича "изтичане на памет" (memory leak).char* buffer = new char[500];
//...
delete buffer; // ERROR: delete only the fist element buffer[0]
Константи и typedefchar* buffer = new char[500];
//...
delete [] buffer; // delete all elements
Често е полезно да се асоциира ново име с някой (обикновено съставен) тип:const double PI = 3.14159265;
const int CUT_OFF[] = {90, 80, 70, 60};
const int N_DAYS = 7;
const int N_HOURS = 24*N_DAYS;
int counter[N_HOURS];
typedef char* BufferPtr; // type BufferPtr is a pointer to char
typedef double Coordinate; // type Coordinate is a double
//...
BufferPtr p; // p is a pointer to a char
Coordinate x, y; // x and y are of type double
class_name.member | class/structure member
selection |
dot (member selection) operator | операция "точка" |
pointer->member |
class/structure member selection | arrow operator |
операция "стрелка" |
array[exp] |
array subscripting |
index (subscript) operator |
операция "индекс" |
exp + exp |
addition |
събиране |
exp - exp | subtraction |
изваждане |
exp * exp | multiplication |
умножение |
exp / exp | division |
деление |
exp % exp | modulo (remainder) |
остатък |
var++ |
post increment |
var-- |
post decrement |
++var | pre increment |
--var | pre decrement |
Операции за сравнение:int a[] = { 0, 1, 2, 3 };
int i = 2;
int j = i++; // j = 2 and then i = 3
int k = --i; // i = 2 and then k = 2
cout << a[k++]; // a[2] (=2) is output; then k = 3
exp < exp |
less than |
по-малко |
exp > exp | greater than |
по-голямо |
exp <= exp | less than or equal to |
по-малко или равно |
exp >= exp | greater than or equal to | по-голямо или равно |
exp == exp | equal to |
равно |
exp != exp | not equal to |
неравно |
! exp |
logical not | логическо "не" |
exp && exp | logical and | логическо "и" |
exp || exp | logical or | логическо "или" |
~exp |
bitwise complement, ex. |
~100010 -> 011101 | побитово отрицание |
exp & exp | bitwise and (conjunction),
ex. |
1001 & 1100 -> 1000 | побитово "и" |
exp ^ exp | bitwise exclusive-or |
1001
^ 1100 -> 0101 |
побитово изключващо "или" |
exp | exp | bitwise or (disjunction) |
1001
| 1100 -> 1101 |
побитово "или" |
exp << exp | shift left | 11001
<< 1 -> 10010 |
преместване наляво |
exp >> exp | shift right |
11001
>> 1 -> 01100 |
преместване надясно |
int i = 10;
int j = 5;
int k = 1;
i -= 4; // i = i - 4; result 6
j *= -2; // j = j * (-2); result -10
k <<= 1; // k = k << 1; result 2
class_name :: member |
class scope resolution |
принадлежност към клас |
namespace_name :: member | namespace scope resolution | принадлежност към именно пространство |
exp ? exp : exp |
conditional expression |
условна операция |
stream >> var |
input stream (overloaded) |
входен поток |
stream << exp |
output stream (overloaded) |
изходен поток |
Operator | Description | Associativity |
:: | scope | Left |
() [ ] -> . sizeof | Left | |
++ -- | increment, decrement | Right |
~ | bitwise complement |
|
! (not) |
unary NOT | |
& * | reference and dereference |
|
..._cast, (type) |
type casting | |
+ - | unary + and - |
|
* / % | arithmetic operators | Left |
+ - | addition, subtraction | Left |
<< >> | bitwise shifts |
Left |
< <= > >= | relational operators | Left |
== != | relational operators | Left |
& |
bitwise and |
Left |
^ | bitwise exclusive-or | Left |
| | bitwise or |
Left |
&& (and) |
logical operator and |
Left |
|| (or) |
logical operator or |
Left |
?: | conditional operator |
Left |
= += -= *= /= %= >>= <<= &= ^= |= |
assignment operators |
Right |
, | comma, separator | Left |
int a = 10, b, c, d;
// right associativity
d = c = b = a; // is equivalent to d = (c = (b = a));
// left associativity
d - c + b - a; // is equivalent to ((d - c) + b) - a;
// precedence
d > c && -b <= a // is equivalent to (d > c) && ((-b) <= a)
void print(int x)
{ cout << x; }
|
bool operator==(const Passenger &x, const Passenger &y) |
|
enum MealType { NO_PREF, REGULAR, LOW_FAT, VEGETARIAN }; |
enum MealType { NO_PREF, REGULAR, LOW_FAT, VEGETARIAN }; |
class Matrix; // Matrix definition comes later
class Vector { // a 3-element vector
private:
double coord[3];
public:
// ...
friend class Matrix; // allow Matrix access to coord
};
class Matrix { // a 3x3 array
private:
double a[3][3];
public:
// ...
Vector multiplyBy(const Vector& v) { // multiply (a * v)
Vector w(0, 0, 0);
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
w.coord[i] += a[i][j] * v.coord[j]; // access private data
return w;
}
};
class Complex {
private:
class Node {
// ...
};
//...
};
stack |
Container with last-in,
first-out access |
стек |
Контейнер с достъп LIFO |
queue |
Container with first-in, first-out access | опашка |
Контейнер с достъп FIFO |
deque |
Double-ended queue |
дек |
Опашка с два края |
vector |
Resizeable array |
вектор |
Масив с променлива дължина |
list |
Doubly linked list |
|
Двусвързан списък |
priority_queue |
Queue ordered by value |
|
Приоритетна опашка |
set,
multiset |
Set |
множество |
|
map,
multimap |
Associative array
(dictionary) |
|
Асоциативен масив (речник) |
vector.cppvector<int> scores(100);
vector<char> buffer(500);
vector<Passenger> passList(20);
vector<int> newScores = scores;
Член-функцииclass Person { // base class
private:
string name; // name
string ssn; // social security number
public:
//...
void print(); // print data
string getName(); // retrieve name
};
class Student : public Person { // derived class
private:
string major; // major subject
int gradYear; // graduate year
public:
//...
void print(); // print data
void changeMajor(string newMajor); // change major
};
Person person(...); // define a person
Student student(...); // define a student
cout << student.getName();// invokes Person::getName()
person.print(); // invokes Person::print();
student.print(); // invokes Student::print();
person.changeMajor("Math"); // ERROR!
student.changeMajor("Math"); // OK
void Person::print() // definition of Person print
{ cout << name << " " << ssn; }
void Student::print() // definition of Student print
{ Person::print(); // first print Person data
cout << major << gradYear;
}
Конструктори и деструкториclass Base {
private:
int priv;
protected:
int prot;
public:
int publ;
};
class Derived: public Base {
void someMemberFunction()
{ cout << priv; // ERROR: private member
cout << prot; // OK
cout << publ; // OK
}
};
class Unrelated {
Base X;
void anotherMemberFunction()
{ cout << X.priv; // ERROR: private member
cout << X.prot; // ERROR: protected member
cout << X.publ; // OK
}
};
[person.cpp]Person::Person(const string &nm, const string &ss)
: name(nm), ssn(ss) {} // initializer list
Student::Student(const string &nm, const string &ss,
const string &maj, int year)
: Person(nm, ss), // initialize Person data members
major(maj), // initialize member
gradYear(year) {} // initialize gradYear
Person::~Person() // Person destructor
{ ... }
Student::~Student() // Student destructor
{ ... }
Student* s = new Student(...);
//...
delete s; // calls ~Student() then ~Person()
int min(int a, int b)
{ return (a < b ? a : b); }
double min(double a, double b)
{ return (a < b ? a : b); }
template<typename T> // parameter list
T min(T a, T b) // returns the minimum of a and b
{ return (a < b ? a : b); }
cout << min(3, 4); // invokes min<int>(3,4)
cout << min(6.9, 3.5); // invokes min<double>(6.9, 3.5)
cout << min('t', 'g'); // invokes min<char>('t', 'g')
template <typename Object>
class BasicVector {
Object* a; // array storing an element
int capacity; // length of array a
public:
BasicVector(int cap = 10) // constructor
{ capacity = cap;
a = new Object[capacity];// allocate array storage
}
Object& elemAtRank(int r) // access element at index r
{ return a[r]; }
// ...
};
BasicVector<int> iv(5); // vector of 5 integers
BasicVector<double> dv(20); // vector of 20 doubles
BasicVector<string> sv; // vector of 10 strings
//...
iv.elemAtRank(3) = 8; // iv[3] = 8;
dv.elemAtRank(14) = 2.5; // dv[14] = 2.5
sv.elemAtRank(7) = "hello"; // sv[7] = "hello"
Изхвърляне (throwing) и прихващане (catching) на изключенияclass MathException { // generic math exception
private:
string errMsg; // error message
public:
MathException(const string& err) { errMsg = err; }
};
class ZeroDivisionException : public MathException {
public:
ZeroDivisionException(const string& err)
: MathException(err) {}
};
class NegativeRootException : public MathException {
public:
NegativeRootException(const string& err)
: MathException(err) {}
};
След изпълнение на catch блока, изпълнението на програмата продължава с първия оператор след последния catch блок.try {
// ...
if (divisor == 0) throw ZeroDivisionException("Division by zero");
//...
}
catch (ZeroDivisionException& zde)
{ // handle division by zero
}
catch (MathException& me)
{ // handle any math exception other than division by zero
}
void calculator() throw(ZeroDivisionException, NegativeRootException)
{
//...
}
void funct1(); // can throw any exception
void funct2() throw(); // can throw no exception
class RuntimeException { // generic run-time exception
private:
string errorMsg;
public:
RuntimeException(const string& err) { errorMsg = err; }
string getMessage() const { return errorMsg; }
};
inline std::ostream& operator<<(std::ostream& out, const RuntimeException& e)
{ return out << e.getMessage(); }