Literatūra
Literatūra
Literatūra
Literatūra
Literatūra
Literatūra
Literatūra
Saturs
Programmēšanas valodas
C valodu saime
C valoda
C++ vēsture
Standartizēšana
OS platformu atbalsts
C++ ievads
C++ programmas failu struktūra
C++ programmas kompilēšana un palaišana
Kompilators
Izpildāma moduļa iegūšana no C++ programmas vispārīgā gadījumā
Izpildāmā moduļa iegūšanas fāzes
Izstrādes vides
Rezervētie vārdi I
Rezervētie vārdi II
Rezervētie vārdi III
Rezervētie vārdi IV
Rezervētie vārdi V
Valoda ir reģistrjūtīga
C++ programmas vienkāršota struktūra
Programmas struktūra
Bibliotēku piesaiste
Funkcija
Komentāri
Komentāra piemērs
Programma 1
Programma 1
Programma 1
Programma ar komentārijiem I
Programma ar komentārijiem II
ESC sekvences
Mainīgo deklarēšana
Datu tipa struktūra
Valodas C++ datu pamattipi
Datu tipu iedalījums
C valodas 4 datu tipu specifikatori
Tipu specifikatori
Datu tipu tabula
Datu tipu vērtību diapazons
Datu tipu vērtību diapazons
Datu tipu vērtību diapazons
Deklarators
Piešķiršanas priekšraksts
Mainīgo deklarēšanas piemēri
Programma 2
Programma 3
Mainīgā izmēra noteikšana
Tipu pārveidošana
Papildus operatori tipa pārveidošanai
Piemērs pārveidošana tipā char
Izteiksmes
Darbības (operācijas)
Skaitliskās funkcijas
Piemēri
Piešķiršanas operatori ar izrēķināšanu
Piešķires operatora savienojumi
Piešķires aritmētiskās operācijas
Inkrementa un dekrementa operācijas
Mainīgā vērtības palielināšanas par 1 pieraksts
Inkrementa piemērs
Attieksmes operators
Attieksmes operāciju rezultāti
Loģiskās operācijas
Loģisko operāciju vērtību tabula
Operatoru prioritātes
Operatori ar bitiem
Konstanšu definēšana (#define) I
Konstanšu definēšana (const) II
Nosacījuma operators
Kontroles jeb sazarošanās struktūra nepilnā
Sazarošanās pilnā
Atkārtošanās struktūras jeb cikli I
Programma
Cikli II
Programma
Cikli III
Programma
Izvēles struktūra
Izvēles struktūras piemērs I
Izvēles struktūras piemērs II
2.82M
Categories: programmingprogramming informaticsinformatics

Ievadlekcija. Программирование на языке С++

1.

Ievadlekcija
© Autors: V. Vagale 2004-2016
1

2. Literatūra


https://en.wikibooks.org/wiki/C%2B%2B_Programming
https://en.wikibooks.org/wiki/C%2B%2B_Programming/Examples
http://www.cplusplus.com/doc/tutorial
http://www.tutorialspoint.com/cplusplus/cpp_overview.htm
http://en.cppreference.com/w/Main_Page
https://isocpp.org/images/uploads/2-Tour-Basics.pdf
http://www.engin.umd.umich.edu/CIS/course.des/cis400/ - visas valodas
http://home.lu.lv/~janiszu/courses/ecpp/cpp01.introduction.pdf
https://www.gamedev.lv/article/c_pamati
2

3. Literatūra

• Уильям Топп, Уильям Форд, Структуры
данных в C++, "Бином" · 1999 г. · 816 стр.
• Шмидский Я.К. Программирование на
языке C++. Самоучитель, 2004. 368 стр.
• Страуструп Б.: Язык программирования
C++. Спец. изд.
BINOM 1999. 1104 стр.
• Харбисон C.П., Стил Г.Л. Язык
программирования C, 528 стр.
• Крупник А.Б. Изучаем C++
СПб.: Питер, 2003. — 251 с.: ил
• Крупник А. Изучаем Си СПб.: Питер, 2002.
— 256 с.: ил.
3

4. Literatūra

• Роберт Седжвик Фундаментальные алгоритмы на
C++. Части 1-4. Анализ. Структуры данных.
Сортировка. Поиск: ДиаСофт, 2002 г. Твердый
переплет, 688 стр.
• Роберт Седжвик, Фундаментальные алгоритмы на
С. Части 1-4. Анализ. Структуры данных.
Сортировка. Поиск "ДиаСофт ЮП" · 2003 г. · 672
стр.
• Майкл Мейн, Уолтер Савитч Структуры данных
и другие объекты в C++ 2-е издание: Вильямс
2002, 832 стр.
4

5. Literatūra


Пол И. Объектно-ориентированное программирование с
использованием С++. - К: ДиаСофт, 1995
Шилдт Г. Теория и практика С++. - СПб.: BHV, 1996
Подбельский В.В. Язык Си++: Учебное пособие. - М.: ФиC, 1996
Р. Лафоре. Объектно-ориентированное программирование в С++.
— СПб: ПИТЕР, 2003 г. — 928 с.
Мейерс С. Эффективное использование С++. - М: ДМК, 2000
Элджер Д. С++: Библиотека программиста. - CПб.: Питер, 1999
Голуб А.И. С и С++. Правила программирования. М: БИНОМ,
1996
Аммерааль Л. STL для программистов на С++. - М: ДМК, 2000.
Дж. Коплиен. Программирование на С++ . — СПб: ПИТЕР, 2005 г.
— 479 с.
5

6. Literatūra


Павловская Т.А. C/C++. Программирование на языке
высокого уровня. — CПб.: Питер, 2001, 2003.
Павловская Т.А., Щупак Ю.А. С/С++. Структурное
программирование: Практикум. — СПб: ПИТЕР, 2002.
Павловская Т.А., Щупак Ю.А. С++. Объектно-ориентированное
программирование: Практикум. — СПб: ПИТЕР, 2004.
Саттер Г. Решение сложных задач на C++. Серия C++ In-Depth,
т.4. — Москва: Издательский дом «Вильямс», 2002 г. — 400 с.
Александреску А. Современное проектирование на С++. Серия
C++ In-Depth, т.3. — Москва: Издательский дом «Вильямс», 2002 г.
— 336 с.
Кениг Э., Му Б. Эффективное программирование на С++. Серия
C++ In-Depth, т.2. — Москва: Издательский дом «Вильямс», 2002 г.
— 384 с.
6

7. Literatūra


Гамма Э., Хелм Р., Джонсон Р., Влиссидес Дж. Приемы объектноориентированного проектирования. Паттерны проектирования. —
СПб: ПИТЕР, 2001 г. — 368 с.
Влиссидес Дж. Применение шаблонов проектирования.
Дополнительные штрихи. — Москва: Издательский дом
«Вильямс», 2003 г. — 144 с.
Шаллоуей А., Тротт Д. Шаблоны проектирования. Новый подход к
объектно-ориентированному анализу и проектированию. —
Москва: Издательский дом «Вильямс», 2002 г. — 288 с.
Штерн В. Основы С++. Методы программной инженерии. —
Москва: ЛОРИ, 2003 г. — 860 с.
В. Лаптев. С++. Экспресс-курс. — СПб: БХВ-Петербург, 2004 г. —
512 с.
Б. Эккель. Философия С++. — СПб: ПИТЕР, 2004 г. — 572 с.
7

8. Literatūra


К. Бек. Экстремальное программирование. — СПб: ПИТЕР, 2002.
К. Бек, М. Фаулер. Экстремальное программирование.
Планирование. — СПб: ПИТЕР, 2003 г. — 144 с.
К. Ауэр, Р. Миллер. Экстремальное программирование.
Постановка процесса. — СПб: ПИТЕР, 2003 г. — 368 с.
К. Лоудон. С++. Краткий справочник. — СПб: ПИТЕР, 2004 г. — 220
с.
С. Уэллин. Как не надо программировать на С++. — СПб: ПИТЕР,
2004 г. — 240 с.
С. Макконнелл. Совершенный код. — СПб: «Питер», 2005. — 896
с.
Стандарт С++: INTERNATIONAL ISO/IEC STANDARD 14882 199809-01, 2003
8

9.

9

10. Saturs

• C++ rašanās vēsture;
• Komentāri;
• Piešķire;
• Datu izvads.
10

11. Programmēšanas valodas


www.tiobe.com
https://en.wikipedia.org/wiki/List_of_C-family_programming_languages
https://www.levenez.com/lang/
11

12. C valodu saime

12

13.

13

14. C valoda

Dennis Ritchie (right) with Ken Thompson
C valoda
Valoda C++ ir izcēlusies no valodas C, kuru (1970)
1972. gadā izstrādājis AT&A Bell Laboratories
līdzstrādnieks Deniss Ričijs (Dennis Ritchie).
C valodai par pamatu tika izmantotas B, BCPL, ALGOL
68 prog. val.
Valodas C sākotnējais uzdevums bija operētājsistēmas UNIX veidošanai un
uzturēšanai.
Tomēr šī valoda kļuva ļoti populāra un to sāka izmantot lietojumprogrammu izstrādei,
kā arī citās operētājsistēmās.
Valoda C uzskatāma par kaut ko, kas ir pa vidu starp ļoti augsta un zema līmeņa
programmēšanas valodām.
Kaut arī sistēmprogrammu rakstīšanai C uzskatāms par ļoti piemērotu, tomēr
lietojumprogrammatūras izstrādē valodai C piemīt vairāki trūkumi – tajā rakstītās
programmas nav tik viegli uztveramas un saprotamas kā citu augsta līmeņa
programmēšanas valodu programmas, turklāt tajā nav daudzu iebūvētu automātiskās
pārbaudes iespēju (resp.,augsta līmeņa konstrukciju) kā pierasts daudzās citās
valodās.
14
https://lv.wikipedia.org/wiki/Deniss_Ri%C4%8Dijs

15. C++ vēsture


Lai kompensētu valodas C nepilnības, 20. gs. 70. gadu beigās – 80. gadu sākumā
AT&A Bell Laboratories līdzstrādnieks Bjerns Stroustrups (Bjarne Stroustrup)
izstrādāja programmēšanas valodu C++, kas daudzos gadījumos ir izrādījusies
labāka par savu priekšteci.
1983 C++ Stroustrup C with Classes
Tajā ieviestas daudzas augsta līmeņa konstrukcijas, kas atvieglo programmētāja
darbu.
Bez tam C++ ir saglabājis savietojamību ar valodu C (lielākā daļa C programmu ir arī
C++ programmas), kas savulaik visticamāk bija izšķiroši, lai C++ iegūtu savu plašo
pielietojumu un popularitāti.
15
https://en.wikipedia.org/wiki/Bjarne_Stroustrup

16. Standartizēšana


ISO International Standard ISO/IEC 14882:2014(E) – Programmin
g Language C++
https://isocpp.org/std/the-standard
16

17. OS platformu atbalsts

http://ithare.com/mmog-server-side-programming-languages/
17

18. C++ ievads


C++ improves on many of C’s features.
C++ provides object-oriented programming (OOP).
C++ is a superset to C.
No ANSI standard exists yet (in 1994).
18

19. C++ programmas failu struktūra

• Programma valodā C++ sastāv:
– no viena vai vairākiem C++ failiem (faila
paplašinājums parasti .cpp vai .cc),
– kā arī iespējami no citiem failiem, no kuriem
tipiskākie ir t.s. hedera (jeb galvas) faili (faila
paplašinājums .h).
• Tātad, triviālā C++ programma sastāv no viena C++
faila.
19

20. C++ programmas kompilēšana un palaišana


Programmas rakstīšanas mērķis parasti ir iegūt izpildāmu moduli
(piemēram .exe failu), kas veic noteiktas darbības.
Lai no programmas iegūtu izpildāmo moduli, nepieciešams
kompilators.
20

21. Kompilators


Kompilators (compiler) ir datorprogramma, kas pārveido noteiktā
programmēšanas valodā uzrakstītu programmu par izpildāmu
moduli (vispārīgā gadījumā – par programmu mašīnkodā, tādu, kuru
dators var tiešā veidā izpildīt).
21

22. Izpildāma moduļa iegūšana no C++ programmas vispārīgā gadījumā

22

23. Izpildāmā moduļa iegūšanas fāzes


1. fāze. Kompilēšana. Katram C++ failam tiek uzbūvēts atbilstošs
objektu fails (faila paplašinājums parasti .obj vai .o), kopumā veidojot
objektu kodu;
2. fāze. Linkošana. No iegūtā objektu koda, kā arī citu programmu, t.sk.
standarta bibliotēku objektu koda tiek izveidots gala produkts –
izpildāmais kods (izpildāmais modulis vai moduļi).
Pilnu izpildāmā koda iegūšanas procesu mēdz saukt arī par
uzbūvēšanu (build), tomēr sarunu valodā, tiek lietots termins
kompilēšana.
Abas izpildāmā koda uzbūvēšanas fāzes parasti tomēr veic viens un tas
pats kompilators.
23

24. Izstrādes vides


Programmas failu organizāciju, kā arī pareizu kompilatora un citu palīgprogrammu
izsaukšanas secību izpildāmā koda iegūšanai parasti nodrošina izstrādes vide,
piemēram:







wxDev-C++ (http://wxdsgn.sourceforge.net/),
Microsoft Visual C++,
Borland C++,
Anjuta,
C++ Editor 1.7 (free),
Eclipse IDE for C/C++ Developers (http://www.eclipse.org/downloads/moreinfo/c.php),
NetBeans IDE 6.9 (http://netbeans.org/features/cpp/),
Izmantojot projektu (project) mehānismu, tādējādi programmētājs var abstrahēties no
šīs shēmas un “ar vienas pogas spiedienu” nonākt no programmas līdz rezultātam.
Otrs bieži lietots variants programmas izpildāmā koda uzbūvēšanai, kas īpaši izplatīts
Unix/Linux platformās, ir t.s. make mehānisms.
https://isocpp.org/get-started
24

25. Rezervētie vārdi I

Keyword
Description
and
alternative to && operator
and_eq
alternative to &= operator
asm
insert an assembly instruction
auto
declare a local variable
bitand
alternative to bitwise & operator
bitor
alternative to | operator
bool
declare a boolean variable
break
break out of a loop
case
a block of code in a switch statement
catch
handles exceptions from throw
char
declare a character variable
class
declare a class
compl
alternative to ~ operator
const
declare immutable data or functions that do not change data
const_cast
cast from const variables
continue
bypass iterations of a loop
25

26. Rezervētie vārdi II

default
default handler in a case statement
delete
make dynamic memory available
do
looping construct
double
declare a double precision floating-point variable
dynamic_cast
perform runtime casts
else
alternate case for an if statement
enum
create enumeration types
explicit
only use constructors when they exactly match
export
allows template definitions to be separated from their declarations
extern
tell the compiler about variables defined elsewhere
false
a constant representing the boolean false value
float
declare a floating-point variable
for
looping construct
friend
grant non-member function access to private data
goto
jump to a different part of the program
26

27. Rezervētie vārdi III

if
execute code based on the result of a test
inline
optimize calls to short functions
int
declare an integer variable
long
declare a long integer variable
mutable
override a const variable
namespace
partition the global namespace by defining a scope
new
allocate dynamic memory for a new variable
not
alternative to ! operator
not_eq
alternative to != operator
operator
create overloaded operator functions
or
alternative to || operator
or_eq
alternative to |= operator
private
declare private members of a class
protected
declare protected members of a class
public
declare public members of a class
register
request that a variable be optimized for speed
reinterpret_cast
change the type of a variable
return
return from a function
27

28. Rezervētie vārdi IV

short
declare a short integer variable
signed
modify variable type declarations
sizeof
return the size of a variable or type
static
create permanent storage for a variable
static_cast
perform a nonpolymorphic cast
struct
define a new structure
switch
execute code based on different possible values for a variable
template
create generic functions
this
a pointer to the current object
throw
throws an exception
true
a constant representing the boolean true value
try
execute code that can throw an exception
typedef
create a new type name from an existing type
typeid
describes an object
typename
declare a class or undefined type
28

29. Rezervētie vārdi V

union
a structure that assigns multiple variables to the same memory location
unsigned
declare an unsigned integer variable
using
import complete or partial namespaces into the current scope
virtual
create a function that can be overridden by a derived class
void
declare functions or data with no associated data type
volatile
warn the compiler about variables that can be modified unexpectedly
wchar_t
declare a wide-character variable
while
looping construct
xor
alternative to ^ operator
xor_eq
alternative to ^= operator
29

30. Valoda ir reģistrjūtīga

Very important: The C++ language is "case sensitive", that means that
an identifier written in capital letters is not equivalent to another one
with the same name but written in small letters.
Thus, for example the variable RESULT is not the same as the variable
result nor the variable Result.
30

31. C++ programmas vienkāršota struktūra

31

32. Programmas struktūra

#include <iostream>
using namespace std;
int main ()
{
cout << "Hello, world!" << endl;
return 0;
}
32

33. Bibliotēku piesaiste

1. #include <iostream.h>
2. #include <iostream>
using namespace std;
3. #include <iostream>
std::cout << "Hello, world!" << endl;
4. #include <cmath> vai #include <math.h>
33

34. Funkcija

int main ()
{
return 0;
}
34

35. Komentāri

• In C,
/* This is a single-line comment. */
• In C++,
// This is a single-line comment.
35

36. Komentāra piemērs

/********************************************************
**
** Programma “Hello, World”
** Izveidota 2007.04.05.
** Labota 2007.04.09.
** Autors Mr. X
**
********************************************************/
36

37. Programma 1

// mana pirmaa programma C++
#include <iostream>
using namespace std;
int main ()
{
cout << "Hello World!";
return 0;
}
37

38. Programma 1

// mana pirmaa programma C++
#include <iostream.h>
using namespace std;
int main ()
{
cout << "Hello World!";
system("Pause");
return 0;
}
38

39. Programma 1

// mana pirmaa programma C++
#include <iostream.h>
using namespace std;
int main ()
{
cout << "Hello World!";
system("Pause>>nul");
return 0;
}
39

40. Programma ar komentārijiem I

/* my second program in C++ with more comments */
#include <iostream>
using namespace std;
int main ()
{
cout << "Hello World! "; // says Hello World!
cout << "I'm a C++ program"; // says I'm a C++ program
system("Pause>>nul");
return 0;
}
40

41. Programma ar komentārijiem II

/* my second program in C++
with more comments */
#include <iostream>
using namespace std;
int main ()
{
cout << "Hello World! “<<endl; // says Hello World!
cout << "I'm a C++ program\n"; // says I'm a C++ program
cout << “Two lines”;
system("Pause>>nul");
return 0;
}
41

42. ESC sekvences

\n
newline
\r
carriage return
\t
tabulation
\v
vertical tabulation
\b
backspace
\f
page feed
\a
alert (beep)
\'
single quotes (')
\"
double quotes (")
\?
question (?)
\\
inverted slash (\)
42

43. Mainīgo deklarēšana


Mainīgā deklarācija ietver šādas informācijas uzrādīšanu par
mainīgo:
– mainīgā tips,
– mainīgā vārds,
– sākuma vērtība (neobligāti).
Mainīgā deklarēšanu veic deklarators.
Ar vienu šādu konstrukciju var deklarēt vienu vai vairākus viena tipa
mainīgos.
Mainīgo deklarēšanu var veikt jebkurā programmas vietā, galvenais,
lai tas notiktu pirms pirmās šo mainīgo izmantošanas.
43

44. Datu tipa struktūra

Datu tips
datu attēlošanas formāts
darbību kopa,
datora atmiņā
kuras var pielietot noteikta
tipa lielumiem
vērtību kopa,
kuras var pieņem
noteikta tipa lielumi
44

45. Valodas C++ datu pamattipi

45

46. Datu tipu iedalījums

Datu tipi
vienkāršie
saliktie
(pamattipi jeb elementārie)
(sarežģītie jeb struktūras)
veselie
simboli
statiskie
skaitļi
(char)
(int)
daļskaitļi
(float)
masīvs ieraksts
dinamiskie
masīvs
koks
kopa
saraksts
46

47. C valodas 4 datu tipu specifikatori

short
īsais
long
garais
signed
ar zīmi
unsigned
bez zīmes
47

48. Tipu specifikatori

integer types
bool
char
signed char
unsigned char
wchar_t
short
short int
unsigned short
int
signed short int
unsigned short int
signed
unsigned
long
signed short
signed int
unsigned int
long int
unsigned long
signed long
signed long int
unsigned long int
floating point types
float
double
long double
optionally supported integer types
long long
unsigned long long
long long int
signed long long
unsigned long long int
signed long long
int
48

49. Datu tipu tabula

Name
Bytes*
Description
Range*
char
1
character or integer 8 bits length.
signed: -128 to 127
unsigned: 0 to 255
short
2
integer 16 bits length.
signed: -32768 to 32767
unsigned: 0 to 65535
long
4
integer 32 bits length.
signed:-2147483648 to 2147483647
unsigned: 0 to 4294967295
int
*
Integer. Its length traditionally depends on the length of the
system's Word type, thus in MSDOS it is 16 bits long,
whereas in 32 bit systems (like Windows 9x/2000/NT and
systems that work under protected mode in x86 systems)
it is 32 bits long (4 bytes).
See short, long
float
4
floating point number.
3.4e + / - 38 (7 digits)
double
8
double precision floating point number.
1.7e + / - 308 (15 digits)
long double
10
long double precision floating point number.
1.2e + / - 4932 (19 digits)
1
Boolean value. It can take one of two values: true or false
NOTE: this is a type recently added by the ANSI-C++
standard. Not all compilers support it. Consult section
bool type for compatibility information.
true or false
2
Wide character. It is designed as a type to store international
characters of a two-byte character set. NOTE: this is a
type recently added by the ANSI-C++ standard. Not all
compilers support it.
wide characters
void
bool
wchar_t
49

50. Datu tipu vērtību diapazons

32 bitu procesoram
+
0
-
veselie skaitļi
ar zīmi
-32768
-2 147 483 648
byte
byte
32767
byte
byte
byte
byte
byte
byte
byte
byte
byte
byte
signed short int = short
enum
2 147 483 647
byte
byte
signed int = int
long int = long
9.22337E+18
long long int = long long
-9.22338E+18
bez zīmes
65 535
4 294 967 295
byte
byte
byte
byte
1.84467E+19byte
byte
unsigned short int = unsigned short
byte
byte
byte
byte
unsigned int = unsigned
unsigned long int = unsigned long
byte
byte
byte
byte
unsigned long long int = unsigned long long
50

51. Datu tipu vērtību diapazons

+
0
-
decimāldaļskaitļi
ar zīmi
3.4E-38
1.7E-308
byte
byte
byte
byte
byte
3.4E+38
float
byte
byte
byte
byte
byte
byte
byte
byte
byte
byte
byte
byte
byte
byte
byte
byte
1.7E+308
doble
byte
3.4E+4932
long double
3.4E-4932
51

52. Datu tipu vērtību diapazons

0
-
+
simboli
ar zīmi
-128
byte
127
signed char = char
bez zīmes
byte
255
unsigned char
ANSI C
1 = sizeof(char) sizeof(short) sizeof(int) sizeof(long)
sizeof(float) sizeof(double) sizeof(long double)
52

53. Deklarators

Deklarators (declarator) ir konstrukcija, kas paziņo, ka noteikts
programmas elements (visbiežāk mainīgais) tiks izmantots programmā.
53

54. Piešķiršanas priekšraksts


Piešķiršana (assignment) ir vērtības ierakstīšana mainīgajā.
Piešķiršanu veic piešķiršanas priekšraksts (assignment
statement), kas ietver sevī piešķiršanas operatoru (vienlīdzības
zīmi).
Piemēri:
x = 5;
x = y = z;
x = (y + z) * 5;
arr[x] = sqrt(y);
54

55. Mainīgo deklarēšanas piemēri


int x;
int x1, x2;
double d;
double e=2007;
int m=7, n=5;
int p=-1, q, r=89;
string s = "Hello, World!";
char v, w='X';
55

56. Programma 2

// operating with variables
#include <iostream.h>
int main ()
{
// declaring variables:
int a, b;
int result;
// process:
a = 5;
b = 2;
a = a + 1;
result = a - b;
// print out the result:
cout << result;
system("pause>>nul");
// terminate the program:
return 0;
}
56

57. Programma 3

// i/o example
#include <iostream.h>
int main ()
{
int i;
cout << "Please enter an integer value: ";
cin >> i;
cout << "The value you entered is " << i;
cout << " and its double is " << i*2 << ".\n";
return 0;
}
57

58. Mainīgā izmēra noteikšana

int x;
cout<<sizeof(int);
cout<<sizeof(x);
58

59. Tipu pārveidošana

int i=66;
char c;
c = 65;
cout << c << endl;
cout << (char)i << endl;
59

60. Papildus operatori tipa pārveidošanai


const_cast
dynamic_cast
reinterpret_cast
static_cast
Nodrošina dažādas pārbaudes.
Tipa pārveidošanas operators const_cast domāts, lai pārdefinētu modifikatorus
const vai volatile, bet citādi tips paliktu tāds pats.
Operators dynamic_cast pārbauda, vai ir iespējama norādītā tipa pārveidošana.
Operators reinterpret_cast domāts viena tipa pārveidošanai par pilnīgi citu un
būtu uzskatāms par vistuvāko klasiskajam variantam. Parasti šo operatoru lieto,
lai pārveidotu savstarpēji nesaderīgus norādes tipus.
60

61. Piemērs pārveidošana tipā char


(char)i
reinterpret_cast<char> (i)
61

62. Izteiksmes

62

63. Darbības (operācijas)


Aritmētiskās
+-*/%
Bitu līmeņa (bitwise) operācijas
<<, >>, |, &, ^, ~
63

64. Skaitliskās funkcijas


pow()
float pow (float base, float p);
Funkcija pow() atgriež vērtību, ko iegūst, argumentu base kāpinot pakāpē p.
ceil()
float ceil (float num);
Funkcija ceil() atgriež mazāko veselo skaitli, kas lielāks vai vienāds par
argumentu num
(noapaļošana uz augšu). Jāievēro, ka atgriežamā vērtība ir ar tipu “ar
peldošo komatu”, tāpēc, lai noapaļoto vērtību piešķirtu mainīgajam ar
vesela skaitļa tipu, papildus jāveic tipa
pārveidošana, piemēram, a = (int)ceil
64

65.


floor()
float floor (float num);
Funkcija floor() atgriež lielāko veselo skaitli, kas mazāks vai vienāds par argumentu num
(noapaļošana uz apakšu). Papildus īpašības sk. pie funkcijas ceil apraksta.
round()
float round (float num);
Funkcija round() atgriež noapaļotu argumenta num vērtību. Papildus īpašības sk. pie
funkcijas
ceil apraksta.
sin, cos, tan, asin, acos, atan, sinh, cosh, tanh
float sin (float arg);
Funkcijas sin() u.c. realizē attiecīgās trigonometriskās funkcijas vai to hiperboliskos
variantus. Argumenta vērtība tiek mērīta radiānos.
65

66.


exp()
float exp (float arg);
Funkcija exp() atgriež argumenta arg eksponenti (skaitļa e kāpinājumu pakāpē arg).
log()
float log (float arg);
Funkcija log() atgriež argumenta arg naturālo logaritmu.
log10()
float log10 (float arg);
Funkcija log10() atgriež argumenta arg logaritmu pie bāzes 10.
sqrt()
float sqrt (float arg);
Funkcija sqrt() atgriež argumenta arg kvadrātsakni.
fabs()
float fabs (float arg);
Funkcija fabs() atgriež argumenta arg absolūto vērtību.
66

67. Piemēri


pow(4, 0.5) // 2 kāpināšana 4 pakāpē 0.5
ceil(4.5) // 5 noapaļošana uz augšu
ceil(-4.5) // -4 noapaļošana uz augšu
floor(4.5) // 4 noapaļošana uz apakšu
floor(-4.5) // -5 noapaļošana uz apakšu
round(4.5) // 5 noapaļošana matemātiski
round(-4.5) // -5 noapaļošana matemātiski
fabs(4.5) // 4.5 absolūtā vērtība (bez zīmes)
fabs(-4.5) // 4.5 absolūtā vērtība (bez zīmes)
67

68. Piešķiršanas operatori ar izrēķināšanu


+= -= *= /= %=
<<= >>= ^= &= |=
i++ // i = i + 1
++i // i = i + 1
i-- // i = i - 1
--i // i = i - 1
i+=k // i = i + k
i-=k // i = i - k
i*=k // i = i * k
i/=k // i = i / k
i%=k // i = i % k
68

69. Piešķires operatora savienojumi

(+=, -=, *=, /=, %=, >>=, <<=, &=, ^=, |=)
value += increase;
is equivalent to
value = value + increase;
a -= 5; is equivalent to a = a - 5;
a /= b; is equivalent to a = a / b;
and the same for all other operations.
69

70. Piešķires aritmētiskās operācijas

Pieņemsim: int c = 3, d = 5, e = 4, f = 6, g = 12;
Piešķires operācija Piemērs
Paskaidrojums
Piešķires rezultāts
+=
c += 7
c=c+7
c = 10
-=
d -= 4
d =d – 4
d =1
*=
e *= 5
e=e*5
e = 20
/=
f /= 3
f=f–3
f=2
%=
g %= 9
g=g+9
g=3
70

71. Inkrementa un dekrementa operācijas

Operācija
Operācijas nosaukums
Izteiksmes
piemērs
Paskaidrojums
+
inkrementa prefiksā
forma
++a
a vērtība tiek palielināta par
1, tad jauno a vērtību
izmanto izteiksmē
+
inkrementa sufiksā
forma
a++
izteiksmē izmanto tekošo a
vērtību, tad a vērtība
tiek palielināta par 1
--
dekrementa prefiksā
forma
--b
b vērtība tiek samazināta par
1, tad jauno b vērtību
izmanto izteiksmē
--
dekrementa sufiksā
forma
b--
izteiksmē izmanto tekošo b
vērtību, tad b vērtība
tiek samazināta par 1
71

72. Mainīgā vērtības palielināšanas par 1 pieraksts

a++;
a+=1;
a=a+1;
are all equivalent in its functionality: the three increase by 1 the value of
a.
72

73. Inkrementa piemērs

Example 1
Example 2
B=3;
B=3;
A=++B;
A=B++;
// A is 4, B is 4
// A is 3, B is 4
In Example 1, B is increased before its value is copied to A. While in Example
2, the value of B is copied to A and B is later increased.
73

74. Attieksmes operators

==, !=, >, <, >=, <=
==
Equal
!=
Different
>
Greater than
<
Less than
>=
Greater or equal than
<=
Less or equal than
74

75. Attieksmes operāciju rezultāti

(7 == 5) would return false.
(5 > 4) would return true.
(3 != 2) would return true.
(6 >= 6) would return true.
(5 < 5) would return false.
75

76. Loģiskās operācijas

!, &&, ||
!(5 == 5) returns false
!(6 <= 4) returns true
!true
returns false.
!false
returns true.
76

77. Loģisko operāciju vērtību tabula

First
Second
Operand
a
Operand
b
result
result
a && b
a || b
true
true
true
true
true
false
false
true
false
true
false
true
false
false
false
false
( (5 == 5) && (3 > 6) ) returns false
( true && false ).
( (5 == 5) || (3 > 6))
( true || false ).
returns true
77

78. Operatoru prioritātes

Priority
Operator
Description
Associativity
1
::
scope
Left
2
() [ ] -> . sizeof
 
Left
++ --
increment/decrement
~
Complement to one (bitwise)
!
unary NOT
&*
Reference and Dereference (pointers)
(type)
Type casting
+-
Unary less sign
4
*/%
arithmetical operations
Left
5
+-
arithmetical operations
Left
6
<< >>
bit shifting (bitwise)
Left
7
< <= > >=
Relational operators
Left
8
== !=
Relational operators
Left
9
&^|
Bitwise operators
Left
10
&& ||
Logic operators
Left
11
?:
Conditional
Right
12
= += -= *= /= %=
>>= <<= &= ^= |=
Assignation
Right
13
,
Comma, Separator
Left
3
Right
78

79. Operatori ar bitiem

op
asm
Description
&
AND
loģiskais un (Logical AND)
|
OR
ieslēdzošais vai (Logical OR)
^
XOR
~
NOT
<<
SHL
loģiskā nobīde pa kreisi (Shift Left)
>>
SHR
loģiskā nobīde pa labi (Shift Right)
izslēdzošais vai (Logical exclusive
OR)
papildinājums - Complement to one
(bit inversion)
79

80. Konstanšu definēšana (#define) I

#define identifier value
#define PI 3.14159265
#define NEWLINE '\n‘
#define WIDTH 100
80

81. Konstanšu definēšana (const) II

const int width = 100;
const char tab = '\t';
const zip = 12440;
In case that the type was not specified (as in the last example) the compiler assumes that
it is type int.
81

82. Nosacījuma operators

condition ? result1 : result2
if condition is true the expression will return result1, if not it will return result2.
7==5 ? 4 : 3
  returns 3 since 7 is not equal to 5.
7==5+2 ? 4 : 3
  returns 4 since 7 is equal to 5+2.
5>3 ? a : b
  returns a, since 5 is greater than 3.
a>b ? a : b
  returns the greater one, a or b.
82

83. Kontroles jeb sazarošanās struktūra nepilnā

if (condition) statement
if (x == 100) cout << "x is 100";
if (x == 100)
{
cout << "x is ";
cout << x;
}
83

84. Sazarošanās pilnā

if (condition) statement1 else statement2
if (x == 100) cout << "x is 100";
else cout << "x is not 100";
if (x > 0) cout << "x is positive";
else
if (x < 0) cout << "x is negative";
else cout << "x is 0";
84

85. Atkārtošanās struktūras jeb cikli I

while (expression) statement
while (n>0)
{
cout << n << ", ";
--n;
}
85

86. Programma

// custom countdown using while
#include <iostream.h>
int main ()
{
int n;
cout << "Enter the starting number > ";
cin >> n;
while (n>0)
{
cout << n << ", ";
--n;
}
cout << "FIRE!";
return 0;
}
86

87. Cikli II

do statement while (condition);
do
{
cout << "Enter number (0 to end): ";
cin >> n;
cout << "You entered: " << n << "\n";
}
while (n != 0);
87

88. Programma

#include <iostream.h>
int main ()
{
unsigned long n;
do
{
cout << "Enter number (0 to end): ";
cin >> n;
cout << "You entered: " << n << "\n";
} while (n != 0);
return 0;
}
88

89. Cikli III

for (initialization; condition; increase) statement;
for (int n=10; n>0; n--)
{
cout << n << ", ";
}
89

90. Programma

// countdown using a for loop
#include <iostream.h>
int main ()
{
for (int n=10; n>0; n--)
{
cout << n << ", ";
}
cout << "FIRE!";
return 0;
}
90

91. Izvēles struktūra

switch (expression)
{
case constant1: block of instructions 1;
break;
case constant2: block of instructions 2;
break;
.
.
.
default: default block of instructions;
}
91

92. Izvēles struktūras piemērs I

switch example
switch (x)
{
if-else equivalent
if (x == 1) { cout << "x is 1"; }
else
case 1:
cout << "x is 1";
break;
case 2:
cout << "x is 2";
break;
if (x == 2) { cout << "x is 2"; }
else
{ cout << "value of x unknown"; }
default: cout << "value of x
unknown";
}
92

93. Izvēles struktūras piemērs II

switch (x)
{
case 1:
case 2:
case 3:
cout << "x is 1, 2 or 3";
break;
default: cout << "x is not 1, 2 nor 3";
}
93
English     Русский Rules