You are on page 1of 45

C++

2004 , markos@debian.org
, nuclear@siggraph.org
: GNU FDL

1. C++
(.. C, C++, PASCAL)

. ,
, .
,
,
Windows Macintosh. ,
(source code)
.
(compile) & (link)


C++ Java.

(source code)


(source code)

C++ compiler

Java compiler


(Native code)

Java Bytecode

Java Virtual
Machine (JVM)

(CPU)
(Procedural Structured
Programming)

C, PASCAL, FORTRAN
C++

.
(code-centric ).
( , )
.
(Object-Oriented Programming)

(Java, Eiffel, Smalltalk


C++) .
(data-centric)
.

.

.

.

. , , , .
. .
/,

.
,
.
,
. ,
( ).

. ,
( .. , , ).
.
,
:

Encapsulation ()

.

Polymorphism ()

,
.

Inheritance ()

ks
re
e

oo
ks

4G

eB

C++

.g


.
,
.

2. C++
, C++
.
, , .

.

.
-' - .
:
type var;

type var .
C++
( ).

,
. ,
, loop for/while/do if/else/switch.
:
type var1;
if () {
// var1 ().
// var2 ().
type var2;
// var2 ()
}
// var1 ()
// var2 ()

C++ C.
C++
bytes, PC (32-bit ):

( bytes)

char

-128 127

short

-32,768 32,767

int/long

-2,147,483,648 -2,147,483,647

-9,223,372,036,854,775,808
-9,223,372,036,854,775,807

1.4 * 10-45 3.4 * 1038

long long
float

C++

( bytes)

double

4.9 * 10-324 1.8 * 10308

bool

true / false

wchar

string

char, short, int, long, long long


, float, double
(. ). bool
true false. wchar 2 bytes
Unicode (UTF-16 ).
:
int an_integer;
an_integer = 10;
long a_long = an_integer *1000;
double verysmallnumber = 0.000000000003;
bool am_i_hungry = false;
char alpha = 'a';
string text = this is a text;

unsigned

C++ C, Java,
char, short, int, long, long long
. bit (sign)
,
.
unsigned .
:

( bytes)

unsigned char

0 255

unsigned short

0 65,535

unsigned int/

0 4,294,967,295

unsigned long

unsigned long long

0 18,446,744,073,709,551,615

(constants)

,
, .
( ) const. ,
const double pi = 3.1415;

C++

(operators)


.
. 4 C++ (
, ).

++

--

,
(
, ). :
int x = 10;
x++; // x 11
x--; // 10

,
, :
int
int
x =
int

x = 10;
y = x++;
10;
z = ++x;

//
//
//
//

x 10
y 10, x 11
x 10
z 11, x

C++

==

!=

>

<

>=

<=

&&

Short-circuit AND

||

Short-circuit OR

NOT ()


.
,
(alpha == true) && (beta == 1)

(false) ,
.
.


.
. :
int x = 4;
x = 10;
x += 20; ( x = x + 20, 30)
x /= 10; ( x = x / 10, 3).

x += y

x = x + y

x -= y

x = x - y

x *= y

x = x * y

x /= y

x = x / y

x %= y

x = x % y

x &= y

x = x & y

x |= y

x = x | y

^=

x = x ^ y

(Expressions)

, ,
.
C++ (int, long, double, bool, )
C++

(.. string).
:
int b = 10, i;
i = 2*b*b; ( )
if (b * b <= 100 && i > 0)
cout << The expression is true << endl;
string a = "ena, dyo";
string b = a + string(", testing");

Pointers & References

C C++
.
,
. ,
pointers references. references
pointers
. pointers
new ( ).
a string,
(reference) string
& . &a
a. , b pointer string,
*, *b
string, b string.
string a(Hello), *b;
b = &a;
cout << a << endl;
cout << *b << endl;


.
&a

a = Hello

C++

3.

.

.
if

if
:
if ()
{
;
}
else
{
;
}

if ,
:
if (x == 1) {
cout << x is one. << endl;
} else if (x == 2) {
cout << x is two. << endl;
} else if (x == 3) {
cout << x is three. << endl;
} else if (x == 4) {
cout << x is four. << endl;
} else {
cout << x is not between 1-4. << endl;
}

switch

switch
.
switch, :
switch (x) {
case 1;
cout <<
break;
case 2;
cout <<
break;
case 3:
cout <<
break;
case 4:
cout <<
break;
default:
cout <<
break;
}

C++

x is one. << endl;


x is two. << endl;
x is three. << endl;
x is four. << endl;
x is not between 1-4. << endl;

break. break
break switch.
.
switch (x)
case
case
case
case

{
1;
2;
3;
4;
cout << x is between one and four. << endl;
break;
case 5;
case 6;
case 7;
case 8;
cout << x is between five and eight. << endl;
break;
default:
cout << x is not between one and eight. << endl;
break;
}

for

for (loop) .
for,
( C).
:
for ( ; ; ) {
;
}

(initialization) loop
(condition). ,
(iteration)
. , ...
:
for (int i = 1; i < 20; i += 3)
cout << i << endl;
}

:
1
4
7
10
13
16
19

,
for.
';'. :
C++

int x = 10;
for (; x < 5; x++) {
cout << x << endl;
}
double y = 20000; // (y = pi)
for (; y >= 10.0;) {
// y
// y.
// for loop y 10.0
cout << y);
y = sqrt(y);
}
for (;;) { // infinite loop
wait_for_signal();
}

while

while for
,
:
while () {
;
}

:
bool exit_from_loop = false;
while (exit_from_loop == false) {
//
read_bytes(file1);
//
write_bytes(file2);
if (file_empty(file1) == true)
exit_from_loop = true;
}

do/while

do/while while, ,
loop
.
do {

;
} while ();

:
int x = 10;
do {
cout << x << endl;
x++;
} while (x <10);

:
10

C++

10

loop
(x < 10).
break/continue

loop
. .. infinite loop,
(signal) (.. Control-C).
for (int i = 1; i < 20; i += 3)
if ( i*i > 100)
break;
cout << i << endl;
}

:
1
4
7
10

break loops, for, while, do/while.


break continue,
iteration loop. iteration.
:
for (int i = 1; i < 20; i++) {
// ()
if ( i % 2 == 0)
continue;
cout << i << endl;
}

:
1
7
13
19

C++

11

4.Classes
Class: Car

Instance of Car
Object:
Audi TT

Instance of Car
Object:
Jaguar XK8

Instance of Car
Object:
Ferrari Modena

Instance of Car
Object:
Bertona Bella

C++
.

(instance) . ,

. , ,
, ,
,
(, , , ).
( /
). , .
C++ class. ,
Car:
class Car
{
(/)
(/)
};

( !)
member variables


. ,
, ,
. ,
,
.

C++

12

Car, :
class Car
{
//
float steering_angle;
// (0 = , 100 = !)
float gas_pedal;
// (0 = , 100 = !)
float break_pedal;
// (0 = ,
// 100 = !)
float clutch;
// ( : 0, 1,2,3,4,5,
// 0 = , -1 = )
int gear;

// ,
//
float acceleration, speed, rpm;


, .
,
. ,
,
, float.
, , Car.

. '
interface . interface
(member methods).
member methods

(methods) , ()
.
,
.
, ,
,
,
.

C++

13

Car :
// , <relative_angle>
// .
void turn_wheel(float relative_angle);
//
void press_gas_pedal(float amount);
//
void press_break_pedal(float amount);
//
void press_clutch_pedal(float amount);
// . true
// false (.. 5 ).
bool change_gear(int new_gear);
// ,
//
float get_acceleration();
float get_speed();
float get_rpm();

, ,
(float) get_*(), bool
change_gear(). void
.
,
' .

,
.

(implementation).
( implementation , .cpp) ,
turn_wheel() car.cpp:
void Car::turn_wheel(float relative_angle)
{
steering_angle += relative_angle;
if (steering_angle <= -720.0)
steering_angle = -720.0;
if (steering_angle >= 720.0)
steering_angle = 720.0;
}


, 2
.
, (.. ),

.

C++

14

C++, ,
, .h .hpp,
-
, - .cpp .cxx.
Car , Car.h
Car.cpp.
,
,
.

, /
(instances) . C++,
, .
new C++.
new , ,
(pointer) ,
(0).
( ). Car
(
acar , anothercar ):
Car acar();
Car *anothercar = new Car();

constructor ,
:
Car acar;
Car *anothercar = new Car;

anothercar,
. :
Car *anothercar;
anothercar = new Car;

( )
, :
// acar
acar.steering_angle
// anothercar
anothercar->steering_angle
// acar 13.4 .
acar.turn(13.4);
// acar
float speed = acar.get_speed();
// anothercar 32
anothercar->turn(-32.0);

C++

15

// anthercar
bool result = anothercar->ghange_gear(-1);

pointer
'->' ( .. ),
'.'.
( ).
C++
.
','.
Constructors

( new),
C++, ,
, (constructor).

.
,
, SQL,
(sockets) server
.

( ,
void).
, Car, :
Car::Car()
{
steering_wheel = 0.0;
gas_pedal = 0.0;
break_pedal = 0.0;
float clutch = 0.0;
int gear = 0;
acceleration = 0.0;
speed = 0.0;
rpm = 0.0;
}

, (initialization)
.
,
.
,
(engine_cc: , engine_hp: ) ,
:
Car::Car(int cc, int hp)
{
engine_cc = cc;
engine_hp = hp;
//
}

C++

16

.
constructor overloading
C++, method overloading (
).
Destructors

C++, , (
delete)
( , ,
threads, , ).
(destructor). destructor
~. Car,
~Car().
,
.
( ,
, ),
(.. , , ).
this

,
,
. ,
.
this
( ).
this, turn_wheel() :
void turn_wheel(float relative_angle)
{
this->steering_angle += relative_angle;
if (this->steering_angle <= -720.0)
this->steering_angle = -720.0;
if (this->steering_angle >= 720.0)
this->steering_angle = 720.0;
}

this
, .
Method Overloading

,
.
/ .
, turn_wheel()
int float. C
/,
:
void Car::turn_wheel_int(int relative_angle)
{

C++

17

this->steering_angle += (float) relative_angle;


if (this->steering_angle <= -720.0)
this->steering_angle = -720.0;
if (this->steering_angle >= 720.0)
this->steering_angle = 720.0;

void Car::turn_wheel_float(float relative_angle)


{
steering_angle += relative_angle;
if (steering_angle <= -720.0)
steering_angle = -720.0;
if (steering_angle >= 720.0)
steering_angle = 720.0;
}

, .
turn_wheel_int() :
void Car::turn_wheel_int(int relative_angle)
{
turn_wheel_float((float) relative_angle);
}

,
,
debugging,
. ObjectOriented Java C++ Method Overloading.
method overloading,
.
, :
void Car::turn_wheel(float relative_angle)
{
steering_angle += relative_angle;
if (steering_angle <= -720.0)
steering_angle = -720.0;
if (steering_angle >= 720.0)
steering_angle = 720.0;
}
void Car::turn_wheel(int relative_angle)
{
turn_wheel((float) relative_angle);
}

turn_wheel()
.
' ' , ( void
) .

C++

18

5.

C++
, .
C++, ( C)
.

.
C.
C++ :
type table[size];

type
(bool, char, short, int, long, float, double,
char) . size
table.
C,
table[i], i .
C C++
(0) size-1. A 10
A[0] A[9].
Java
.length, C++
sizeof().
bytes .
:
int data[10];
int datasize = sizeof(data) / sizeof(int);
int i;
cout << Size of array data: << sizeof(data) / sizeof(int) << endl;
for (i = 0; i < datasize; i++) {
data[i] = i*i;
cout << data[ << i << ] = << data[i] << endl;
}

:
Size of
data[0]
data[1]
data[2]
data[3]
data[4]
data[5]
data[6]
data[7]
data[8]
data[9]

array data: 10
= 0
= 1
= 4
= 9
= 16
= 25
= 36
= 49
= 64
= 81

,
,
C++

19

:
int dataset[] = { 22, 3, 54, 43, 199, 20, 20, 67, 7, 80 };


C++, .
, :
int
int
int
for

twodim[4][4];
arraysize = 4;
i, j, counter = 1;
(i = 0; i < arraysize; i++) {
for (j = 0; j < arraysize; j++) {
twodim[i][j] = counter;
counter++;
cout << twodim[i][j] << ;
}
cout << endl;

:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16

twodim[1][2]

twodim[3][1]

9 10 11 12
13 14 15 16

Strings

strings
cout. strings (C, PASCAL)
, C++ strings ,
string ( namespace std). ,
C, strings
(char * char []).
cout,
string,
, ( new).
std::string str(Hello);
std::string str2 = there;
std::string *str3 = new std::string(Hello there);

C++

20

cout << str << str2 << endl;


cout << *str2 << endl;

string ,
string.
:

bool empty()

true string .

int length()

( ) string.

reference operator[](int
index)

(reference)
index string.

int compare(string &str)

string.
(. compare())
str,
, ,
sttring
str.

int find(string &str)

str string.

, -1.

int find_last_of(string str)

str string.

, -1.

strings:
string str1(Hello
string str2 = One
string str3 = C++
string *str4 = new
int index, result;

there, from C++!);


two three four;
strings are cool!;
string(str3);

cout << str1 is << str1.length() << characters long.);


for (int i=0; i < str1.length(); i++)
cout << str1[i] << |;
cout << endl;
if (str3 == *str4)
cout << str3 == str4 << endl;
else
cout << str3 != str4 << endl;
if (str3 == str2)
cout << str3 == str2 << endl;
else
cout << str3 != str2 << endl;
result = str3.compare(str1);
if (result < 0)
cout << str3 < str1 << endl;
else if (result == 0)
cout << str3 == str1 << endl;

C++

21

else

cout << str3 > str1 << endl;

index = str1.find(C++);
if (index != -1)
cout << 'C++' exists in str1 in position << index << endl;
else
cout << 'C++' does not exist in str1 << endl;
index = str2.find(C++);
if (index != -1)
cout << 'C++' exists in str2 in position << index << endl;
else
cout << 'C++' does not exist in str2 << endl;
index = str3.find(C++);
if (index != -1)
cout << 'C++' exists in str3 in position << index << endl;
else
cout << 'C++' does not exist in str3 << endl;

:
str1 is 22 characters long.
H|e|l|l|o| |t|h|e|r|e|,| |f|r|o|m| |C|+|+|!|
str3 == str4
str3 != str2
str3 < str1
'C++' exists in str1 in position 18
'C++' does not exist in str2
'C++' exists in str3 in position 0

C++

22

6.

C++. ,

.
main()

C C++, main().

, .
Java, .
C++:
#include <iostream>
int main(int argc, char *argv[]) {
std::cout << hello everyone << std::endl;
}

#include
stream C++, cin, cout cerr (
). iostream.
int main()
.
, (0)
(5, 10, )
.
,
(crash).
argc, argv args[] Java.

. C/C++
.
argv[] strings C ( char
string),
argc. argc, argv.
cout ,
stream (standard output)
( print, printf,
write, ). streams C++ .
endl (new line)
\n ( flush
stream ).
cout endl std
::. namespace
stream cout endl, .
namespace std,
std::, namespace
.
C++

23

namespace
namespace ( std) '::'. ,
(
main())
using namespace std;

:
using namespace std;
#include <iostream>
int main(int argc, char *argv[]) {
cout << hello everyone << endl;
}

.
main()

, main()
argc argv[]. ,
(DOS/Command Prompt
Windows, shell Linux).

:
#include <iostream>
using namespace std;
int main(int argc, char *argv[]) {
for (int i=0; i < argc; i++)
cout << argv[i] << endl;
}

ArgsExample.cpp .
ArgsExample,
:
C:\> ArgsExample hello mate what's up?
ArgsExample
hello
mate
what's up?

(ArgsExample, hello, mate what's


up?) . Java, C/C++
(argv[0]) .
(space,
tab) ,
( what's up?
).

C++

24

7.
Encapsulation

Person
, .. , , email
. ..
, , .
class Person
{
public:
//
string Firstname_, Lastname_;
int Age_;
string Telephone_;
string Email_;

// constructor
Person(string fname, string lname, int age, string tel,
string email)
{
Firstname_ = fname;
Lastname_ = lname;
Age_ = age;
Telephone_ = tel;
Email_ = email;
}

_. ,
,

.
,
:
Person bilbo(Bilbo, Baggins, 111, +306970123456,
bilbobaggins@theshire.net);

, bilbo
Bilbo Baggins, 111 . 306970123456 email bilbobaggins@theshire.net.
.
bilbo,

. , email email_
telephone_. :
bilbo.Firstname_
bilbo.Lastname_
bilbo.Age_
bilbo.Email_
bilbo.Telephone_

=
=
=
=
=

;
;
3;
this is definitely not a valid email address;
yeah, try to call this;

!!!

C++

25

;
C++
,
.
, public.
, public
( ). public
. ,
private.
private
, ( ).
, .
Person, private,
:
class Person
{
private:
//
private string Firstname_, Lastname_;
private int Age_;
private string Telephone_;
private string Email_;
public:
...


!
.
, .
.
,
,
( getter/setter ).
, Person get/set
(Age_ Email_):
// Return the age
int Person::getAge()
{
return Age_;
}
// return the Email address
string Person::getEmail()
{
return Email_;
}
// method to set the age of the person
bool Person::setAge(int Age)
{
// check if given Age is non-negative (> 0)
if (Age > 0)
{

C++

26

Age_ = Age;
return true;
} else
return false;

// method to set the email address


bool Person::setEmail(string Email)
{
// call a helper method to check the validity of the email
// address (if it's in the form x@y.z).
// Ideally, the email address should be a class on its own.
if (isValid(Email) == true)
{
Email_ = Email;
return true;
} else
return false;
}

.
email , ,
email ( x@y.z).

. ..
,
. O,
,
(.. setTelephone()).
Inheritance


. ,
.
,
Person . Person
, .. ,
, ,
/ .
Person

( ).
,
.
/ , ;

. Person
(Clerk)
(Teacher).
Person.
Person.
(
C++

27

):
class Clerk : public Person
{
private:
string JobTitle_;
string CompanyName_;
string JobAddress_;
string JobEmail_;
string JobTel_;
string JobFax_;
string JobDescription_;
public:
Clerk(string fname, string lname, int age, string tel,
string email, string jobtitle, string companyname,
string jobaddress, string jobemail,
string jobtel, string jobfax,
string jobdescription)
{
Firstname_ = fname;
Lastname_ = lname;
Age_ = age;
Telephone_ = tel;
Email_ = email;
JobTitle_ = jobtitle;
CompanyName_ = companyname;
JobAddress_ = jobaddress;
JobEmail_ = jobemail;
JobTel_ = jobtel;
JobFax = jobfax;
JobDescription_ = jobdescription;
}
// get/set
// ...
...

//
// .
string getInfo() {
return (getFirstname()+ +getLastname()
+ works at +CompanyName_
+, at +JobAddress_
+.\n Email: +getEmail()+\n
+Tel: +JobTel_);
}

, Teacher:
class Teacher : public Person
{
private:
string Title_;
string School_;
string SchoolAddress_;
string SchoolTel_;
string CourseName_;
string CourseDescription_;
public:
Teacher(string fname, string lname, int age, string tel,
string email, string title, string school,
string schooladdress, string schooltel,

C++

28

string coursename, string coursedescription)


Firstname_ = fname;
Lastname_ = lname;
Age_ = age;
Telephone_ = tel;
Email_ = email;
Title_ = title;
School_ = school;
SchoolAddress_ = schooladdress;
SchoolTel_ = jobtel;
CourseName_ = coursename;
CourseDescription_ = coursedescription;

}
// get/set
// ...
...

//
// .
string getInfo() {
return (getFirstname()+ +getLastname()
+ teaches +CourseName_+ at +School_
+, +SchoolAddress_+.\n
+Email: +getEmail()+\n
+Tel: +SchoolTel_);
}

get() Person
( private).
private,
. .
;
:
Person bilbo(Bilbo, Baggins, 111, +306970123456,
bilbobaggins@theshire.net);
Clerk sam( Samwise, Gamgee, 33, +30697654321,
samgamgee@theshire.net,
Gardener, Baggins Inc.,
Bag End, Hobbiton, The Shire,
gardener@baggins.com,
+302103456789, +302103456780,
Garden Dept. Director);
Teacher pippin( Peregrin, Took, 27, +30690090090,
pippin@theshire.net, Dr.,
King's College, Hobbiton,
+30210000001, Philosophy,
Deal with the important matters of life, eg. what do we
eat?);

,
,
( ):
cout << bilbo has email address: << bilbo.getEmail()) << endl;

:
C++

29

bilbo has email address: bilbobaggins@shire.net

:
cout

<< sam works as a << sam.getJobTitle() << at


<< sam.getCompanyame()) << endl;

:
sam works as a Gardener at Baggins Inc.

, :
cout

<< pippin teaches << pippin.getCourseName() << at


<< pippin.getSchool()) << endl;

:
pippin teaches Philosophy at King's College

, :
cout << sam's private telephone is << sam.getTel() << endl;
cout << pippin is << pippin.getAge() << years old << endl;

:
sam's private telephone is +30697654321
pippin is 27 years old

Person !!!
!
,
(code reusability).
,

, .
Polymorphism Virtual Methods


; ,
getInfo(),
. ,
Person, getInfo().
getInfo() Person, .. :
string Person::getInfo() {
return (getFirstname()+ +getLastname()
+is +getAge()+ years old);
}

: getInfo()
;
Clerk
Teacher. C++ ( Java), override
. virtual,
, :
C++

30

virtual string getInfo() {


return (getFirstname()+ +getLastname()
+is +getAge()+ years old);
}

, getInfo()
.
, :
cout << bilbo.getInfo() << endl;
cout << sam.getInfo() << endl;
cout << pippin.getInfo() << endl;


Bilbo Baggins is 111 years old
Samwise Gamgee works at Baggins Inc., at Bag End, Hobbiton, The Shire.
Email: gardener@baggins.com
Tel: +302103456789
Peregrin Took teaches Philosophy at King's College, Hobbiton.
Email: pippin@theshire.net
Tel: +30210000001

; (
getInfo()) . Person
getInfo() (Bilbo Baggins is 111 years old)
Clerk Teacher .
, getInfo() Clerk, getInfo()
sam Samwise Gamgee is 33 year old.
Clerk
getInfo(), , .
Method Overriding
. virtual methods virtual (virtual
classes). virtual
.

//
.

. (bilbo, sam, pippin).
Person* who[3];
who[0] = &bilbo;
who[1] = &sam;
who[2] = &pippin;
for (int i=0; i < who.length; i++)
cout << who[i]->getInfo() << endl;

,
Person
. sam Clerk pippin
Teacher. who;
Person, Clerk Teacher .
Clerk Person, Teacher
Person. Clerk Teacher.
C++

31

Clerk Teacher Person,


. Person, getInfo()
.
(
);
.
. getInfo()
Teacher :
Teacher(string fname, string lname, int age, string tel,
string email, string title, string school,
string schooladdress, string schooltel,
string coursename, string coursedescription)
{
Person(fname, lname, age, tel, email);
Title_ = title;
School_ = school;
SchoolAddress_ = schooladdress;
SchoolTel_ = jobtel;
CourseName_ = coursename;
CourseDescription_ = coursedescription;
}
string getInfo() {
return (Person.getInfo()
+ and teaches +CourseName_+ at +School_
+, +SchoolAddress_+.\n
+Email: +getEmail()+\n
+Tel: +SchoolTel_);
}

(initialize)

. , getInfo(),
. ..
getInfo() Person,
getInfo() Teacher,
Person..
method overriding
. ,
. ( )
(method overloading)
.
Pure Virtual Classes


, . ,
,
method overriding.

' . C++ pure virtual
Java abstract.
.

C++

32

.
( )
. :
class Car {
...
// . true
// false (.. 5 ).
virtual bool change_gear(int new_gear) = 0;
...
}
class FerrariModena extends Car {
...
bool change_gear(int new_gear) {
//
}
...
}

C++

33

8. Streams
.

,
. .. BeOS
.
, C FILE (struct,
) .
pointers FILE
.

(,
, ). ,
.
C++, streams.
, bytes
. streams
,

.
fstream
ifstream, ofstream. , ifstream
(input file stream),
ofstream (output file stream). fstream
.
fstream

fstream ( ),
, flags
.
:

bool good()
bool bad()

good() true
(
/) false . bad()
.

bool eof()

true
.

void flush()


buffers
.

int get()

istream &getline(char *buf,


int num)


buf, num
.
.

C++

34

int gcount()



get(), read().

istream &read(char *buf, int


num)


buf, num
.
.

ostream &write(char *buf, int


num)

buf
, num .
.

void seekg(int offset,


origin)
void seekp(int offset,
origin)


(seekg) (seekp). streams C++
,
.

int tellg()
int tellp()


(tellg) (tellp).

fstream
, :
(byte)
blocks 256KB .
#include <fstream>
#include <iostream>
using namespace std;
int main(int argc, char *argv[]) {
// 3 .
// C++ argv[0]
// .
if (argc != 3) {
cout << "Usage: CopyFile <from> <to>" << endl;
return 0;
}
// <from> (
// argv[1]).
//
// .
ifstream fin(argv[1]);
if (fin == 0) {
cout << "Error: Input file cannot be opened for reading!" << endl;
return 10;
}
// <to> (
// argv[2]).
//
// .
ofstream fout(argv[2]);
if (fout == 0) {

C++

35

cout << "Error: Output file cannot be opened for writing!" << endl;
return 10;

// ,
// seekg() tellg(). seekg() ,
// tellg() .
// (cursor)
// offset 0 (ios::end)
// tellg(). .
fin.seekg(0, ios::end);
size_t finsize = fin.tellg();
cout << "Input file size: " << finsize << endl;
// ,
// , offset 0 bytes ios::beg).
fin.seekg(0, ios::beg);
// fin fout.
// byte byte

int c;
int percent = 0;
while (fin.eof() == false) {
c = fin.get();
if (fin.eof() == false)
fout.put(c);
cout << "Copy Completed
percent++;
}
fin.close();
fout.close();
return 0;

// ;
// byte
//
// byte
: " << 100*percent/finsize << "\r";

40MB 20 .
.
4 !
while:
// fin fout.
// block
size_t bufsize = 262144;
// block
char buf[bufsize];
// buffer bytes
int count;
// bytes
int total = 0;
while (fin.eof() == false) {
// ;
fin.read(buf, bufsize);
// bufsize bytes
count = fin.gcount();
//
if (count)
// 1 byte
fout.write(buf,count); // fout
cout << "Copy Completed : " << 100*total/finsize << "\r";
total += count;
}

<<, >>

, fstream
, << >>
C++

36

(>>) (<<) .
() cout. cout
ostream ( ofstream)
(stdout). cin
istream ( ifstream) stdin,
cerr stderr.
. fin, fout
ifstream ofstream :
#include <fstream>
#include <iostream>
using namespace std;
int main() {
ifstream fin("data.txt");
if (fin == 0) {
cout << "Error: could not open file data.txt" << endl;
return 10;
}
ofstream fout("output.txt");
if (fout == 0) {
cout << "Error: could not open file output.txt" << endl;
return 10;
}
// .
string name;
double age;
//
while (fin.eof() == false) {
//
fin >> name >> age;
if (fin.eof() == false) {
//
cout << " " << name << " " << age << " ." << endl;

// output.txt
fout << " " << name << " " << age << " ." << endl;

data.txt .. :
29.7
34.4
6.5
803.4

output.txt :

29.7 .
34.4 .
6.5 .
803.4 .

C++

37

Stringstreams

C, , string
sprintf, printf
(stdout) fprintf . ,
streams << >> C++ strings.
stringstream ( sstream),
fstream.
:
#include <string>
#include <sstream>
#include <iostream>
using namespace std;
int main() {
stringstream formatted;
// .
int data[] = {10, 5, 4, 3, 8, 11};
string names[] = {"one", "two", "three", "four", "five", "six"};

for (int i=0; i < 6; i++) {


formatted << "Name: " << names[i] << ", value: " << data[i] << endl;
}
cout << formatted.str();

:
Name:
Name:
Name:
Name:
Name:
Name:

one, value: 10
two, value: 5
three, value: 4
four, value: 3
five, value: 8
six, value: 11

:
cout << formatted.str();

str() stringstream
string .
stringstream .

C++

38

9. (templates)
(templates) C++,
STL( ),
(compile-time) (runtime), ,
.
.
, ,
/ .
;
(..
int string)
. ,
.
, ,
!
.
, , ,
,
. ..
.
- template
<>.

( ):
#include <iostream>
using namespace std;
// list template
// data_t ( ,
// ).
template<class data_t> class list {
// item data_t
data_t item;
// next
//
list *next;
public:
// ( data_t)
list(data_t d);
//
// add()
void add(list *node) {
node->next = this;
return;
}

C++

39

// get_next()
list *get_next() {
return next;
}

};

// get_data item.
// (.. char data_t
// char, string, .
data_t get_data() {
return item;
}

// ,
// .
// template brackets <data_t>
//
template<class data_t> list<data_t>::list(data_t d) {
// item d
item = d;
// (
next = 0;
}
int main() {
// list.
// data_t char
list<char> start('a');
// (pointers)
list<char> *p, *last;
// last
// ,
last = &start;
for (int i=1; i < 26; i++) {
//
// 'a' + i.
// ( new.
p = new list<char>('a' +i);
// .
p->add(last);

// .
// .
last = p;

//
p = &start;
while (p) {
// ( get_next()
// ,
// .
cout << p->get_data() << ", ";
// .
p = p->get_next();

}
cout << endl;

C++

40

return 0;

.
a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z,

list, templated,
char.
Standard Template Library (STL)

STL


.
,
strings.
STL : containers,
iterators.


(.. ).
containers

containers
( )
,
, ( containers), .
containers vector, list, queue, stack set,
containers map, multimap.
containers ,
.
algorithms

containers ,
. STL
containers
(algorithms).
containers,
, . ..
container,
container string,
( <, ==, >).
STL , (sort,
stable_sort), container
(copy, copy_backward, unique_copy, unique_copy_if),
(fill, fill_n), container
(find, find_end, find_first_of, find_if),
(count, count_if),
C++

41

(for_each, transform), (set_union, set_intersection),


(max_element, min_element),
container
container (remove, remove_if, remove_copy, remove_copy_if, replace, replace_if,
replace_copy, replace_copy_if), .
iterators

container
. iterators,
STL . iterators
pointers , .. forward backward
iterators container ,
input output iterators streams .
,
iterators container,
container (begin() end()).
container vector


STL. container vector.
#include
#include
#include
#include

<string>
<vector>
<iostream>
<fstream>

// std:: ...
using namespace std;
// Person ,
// . ,
// public.
class Person {
public:
// string, age
string name_;
int age_;

};

// constructor
//
Person(string n, int a) {
name_ = n;
age_ = a;
}

// main()
int main() {
// vector Person
// (addressbook)
vector<Person> addressbook;
// input age.
// const linesize "" (constant)
// .

C++

42

const int linesize = 100;


char input[linesize];
int age;
// 10 (, )
for (int i=0; i < 5; i++) {
// getline()
// ,
// input.
cout << "Enter name: ";
cin.getline(input, linesize);
// .
// getline , >> cin.
cout << "Enter age: ";
cin >> age;
// :
// * Person
// (input)
// age.
// constructor Person(input, age).
// *
// vector<Person> addressbook.
// push_back().
addressbook.push_back(Person(input, age));

//
// newline '\n', cin >> age
// .
// loop. (
//
//
// ...
cin.getline(input, linesize);

//
ofstream fout("address.txt");
if (fout == 0) {
cout << "Error! cannot open file address.txt" << endl;
return 10;
}
// addressbook
// fout. for. size()
// addressbook () vector.
cout << "Writing results to file address.txt" << endl;
for (int j=0; j < addressbook.size(); j++) {
fout << addressbook[j].name_ << " is "
<< addressbook[j].age_ << " years old" << endl;
}

//
fout.close();
return 0;

:
Enter name: Kostas

C++

43

Enter
Enter
Enter
Enter
Enter
Enter
Enter
Enter
Enter

age: 29
name: Nikos
age: 33
name: Myrsini
age: 27
name: Bilbo
age: 22
name: Gimli
age: 27

address.txt :
Kostas is 29 years old
Nikos is 33 years old
Myrsini is 27 years old
Bilbo is 22 years old
Gimli is 27 years old

, , !

... ;

C++

44

C/C++ Programmer's Reference, 3rd Edition, SCHILDT H., OSBORNE, ISBN 0072227222
C++, BJARNE STROUSTRUP, , ISBN 9603321427,
1200 .
C++: a Beginner's Guide, SCHILDT, OSBORNE, ISBN 0072194677
Thinking in C++ Vol 1, Bruce Eckel, PRENTISH HALL, ISBN 0139798099 (online)
Thinking in C++ Vol 2, Bruce Eckel, PRENTISH HALL, ISBN 0130353132 (online)

C++

45

You might also like