#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
const int cat = 1; // global cat
int main()
{
const int cat = 2; // local cat (to main)
cout << cat; // outputs 2
return 0;
}
int dog = cat; // dog = 1 (from global cat)
Достъп до обект x в именното пространство group дава операция "принадлежност" :: (scope): group::x.namespace myglobals {
int cat;
string dog = "bow wow";
}
int d = myglobals::cat;
using std::cout;или
using myglobals::cat;
using namespace std;
using namespace myglobals;
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;