Sie sind auf Seite 1von 26

2/11/2019

Ho Chi Minh City University of Technology


Department of Electrical and Electronics

1. Basic C++ programming elements


2. Expressions
3. Control flow
4. Functions
5. Classes
6. Object-oriented design

Chapter 1 1

1. Basic C++ programming elements


1.1. A simple C++ program
#include <cstdlib>
#include <iostream>

int main() {
int x,y;
std::cout << “Please enter two numbers: ”;
std::cin >> x >> y;
int sum = x + y;
std::cout << “Their sum is ” << sum << std::endl;
return EXIT_SUCCESS;
}

cstdlib: standard system definition


iostream: definitions needed for input and output
Chapter 1 2

1
2/11/2019

1. Basic C++ programming elements


1.2. Fundamental types
Name Size Range
bool 1 bytes True or false
char 1 bytes Signed: -128 to 127
Unsigned: 0 to 255
short 2 bytes signed: -32768 to 32767
unsigned: 0 to 65535
int 4 bytes signed: -2147483648 to 2147483647
unsigned: 0 to 4294967295
long 4 bytes signed: -2147483648 to 2147483647
unsigned: 0 to 4294967295
float 4 bytes 3.4E +/- 38 (7 digits)

double 8 bytes 1.7E +/- 308 (15 digits)

Chapter 1 3

1. Basic C++ programming elements


1.2. Fundamental types
 Special characters:
 ‘\n’ new line
 ‘\b’ backspace
 ‘\t’ tab
 ‘\0’ null
 ‘\’’ single quote ‘
 ‘\\’ back slash \
 ‘\”’ double quote “

 Long integer
 “L” can be added to indicate a long
integer: 123456789L
 Double
 “E” indicate exponent: 1.2E2 = 1.2 x 102

Chapter 1 4

2
2/11/2019

1. Basic C++ programming elements


1.2. Fundamental types
 Examples:
 int Number = 200;
 char ch = ‘Q’;

 Correct or wrong
char newline = ‘\n’;
unsigned short s = 100000;
long BIGnumber = 314159265L;
double t = 3.14E5

Chapter 1 5

1. Basic C++ programming elements


1.2. Fundamental types
 Enumeration
 User-defined type
 Can hold any of a set of discrete value
 Each element is associated with an integer value
 By default, these values count up from 0

Enum Color {RED, GREEN, BLUE}


Enum Mood {HAPPY = 3, SAD = 1, ANXIOUS = 4,
SLEEPY = 2};

Color skyColor =RED;


Mood myMood = SLEEPY;

Chapter 1 6

3
2/11/2019

1. Basic C++ programming elements


1.3. Pointer, arrays, structures
 Pointer
 Each variable is stored in the computer’s memory at
some location, or address
 A pointer holds the value of such an address.
 Examples: Address Memory
char ch = ‘Q’;
p ‘Q’ ch
char* p = &ch;
cout << *p;
ch = ‘Z’;
cout << *p;

Chapter 1 7

1. Basic C++ programming elements


1.3. Pointer, arrays, structures
 Arrays
 Is a collection of elements of same type
 Examples:
double f[3];
double* p[10]
f[2] = 25.3;
p[4] = &f[2];
cout << *p[4];

Chapter 1 8

4
2/11/2019

1. Basic C++ programming elements


1.3. Pointer, arrays, structures
 Examples for pointers and arrays
char c[] = {‘c’, ‘a’, ‘t’};
char *p=c;
char *q=&c[0];
cout << c[2] << p[2] << q[2];
 Examples for strings
string s = “to be”;
string t = “not” + s;
string u = s + “ or ” + t;
if (s > t)
cout << u;

Chapter 1 9

1. Basic C++ programming elements


1.3. Pointer, arrays, structures
 Structures
 is useful for storing an aggregation of elements.
 Examples
enum MealType {NO_PREF, REGULAR, LOW_FAT,
VEGETARIAN};
struct Passenger {
string name;
MealType mealPref;
bool isFreFlyer;
string freFlyerNo;
};
Chapter 1 10

5
2/11/2019

1. Basic C++ programming elements


1.3. Pointer, arrays, structures
 Allocate a new instance
 Example
Passenger* p;
p = new Passenger;
//…
p->name = “Pocahontas”;
p->mealPref = REGULAR;
p->isFreqFlyer = false;
p->freqFlyerNo = “NONE”;
//…
delete p;
 If an object is allocated with new, it should eventually be
deallocated with delete.
Chapter 1 11

1. Basic C++ programming elements


1.4. Scope and Namespaces
 Constant and Typedef
 Used to associated names with constant quantities
 Examples
const double PI = 3.14159265;
const int CUT_OF[] = {90, 80, 70, 60};

typedef char* BufferPtr;


typedef double Coordinate;
//…
BufferPtr p;
Coordinate x,y;

Chapter 1 12

6
2/11/2019

1. Basic C++ programming elements


1.4. Scope and Namespaces
 Local and Global Scope
 Example
const int cat = 1;

int main() {
const int cat = 2;
cout << cat;
return EXIT_SUCCESS;
}

int dog = cat;

 What is the value of variable “dog”?

Chapter 1 13

1. Basic C++ programming elements


1.4. Scope and Namespaces
 Namespaces is a mechanism that allow a group of related names to
be define in one place.
 Example
namespace myglobal {
int cat;
string dog = “bow bow”;
}
//…
myglobal::cat = 1;

 The Using Statement


 using std::string //makes std::string accessible
 using std::cout //make std::cout accessible
 using namespace myglobals //makes all of myglobals accessible

Chapter 1 14

7
2/11/2019

Assignment
1. If i is an integer and p and q are pointers to
integers, which of the following
assignments cause a compilation error?
a) p=&i;
b) p= *&i;
c) p=&*i;
d) i=*&*p;
e) i=*&p;
f) i=&*p;
g) p=&*&i;
h) q=*&*p;
i) q=**&p;
j) q=*&p;
k) q=&*p;
Chapter 1 15

Assignment
2. Identify the errors; assume in (b) and (c) that s2 has been
declared and assigned a string:

(a) char* f(char *s) {


char ch = ‘A’;
return &ch;
}

(b) char *s1;


strcpy(s1, s2);

(c) char *s1;


s1 = new char[strlen(s2)];
strcpy(s1, s2);

3. What is the difference between if (p==q) {…} and if(*p==*q) {…}

Chapter 1 16

8
2/11/2019

2. Expressions
2.1. Operators

 Arithmetic operators
 exp + exp addition
 exp – exp subtraction
 exp * exp multiplication
 exp / exp division
 exp % exp modulo (remainder)
 Increment and decrement operators
 var++ post increment
 var-- post decrement
 ++var pre increment
 --var pre decrement

Chapter 1 17

2. Expressions
2.1. Operators

 Relational and logical operators


 exp < exp less than
 exp > exp greater than
 exp <= exp less than or equal
 exp >= exp greater than or equal
 exp ==exp equal to
 exp !=exp not equal to
 !exp logical not
 exp && exp logical and
 exp || exp logical or

Chapter 1 18

9
2/11/2019

2. Expressions
2.1. Operators
 Bitwise operators
 ~exp bitwise complement
 exp & exp bitwise and
 exp ^ exp bitwise exclusive or
 exp | exp bitwise or
 exp1 << exp2 shift exp1 left by exp2 bits
 exp1 >> exp2 shift exp1 right by exp2 bits

Chapter 1 19

2. Expressions
2.1. Operators
 Assignment operators
=
 -=
 +=
 *=
 <<=
 Other operators
 bool_exp ? true_exp : false_exp
 smaller = (x<y? x : y);

Chapter 1 20

10
2/11/2019

2. Expressions
2.2. Casting
 is an operation that allows us to change the type of a
variable.
 Examples
int cat = 14;
double dog = (double) cat; //traditional C-style cast
double dog = double(cat); //C++ functional cast
//…
int i1 = 18;
int i2 = 16;
double dv1 = i1/i2;
double dv2 = double(i1)/double(i2);
double dv3 = double(i1/i2);
Chapter 1 21

2. Expressions
2.2. Casting
 Casting operations can vary from harmless to
dangerous, depending on how similar the two types
are and whether information is lost.
 Explicit casting
double d1 = 3.9999;
int i1 = static_cast<int>(d1);
 Implicit casting
int i = 3;
double d = 4.8;
double d3 = i/d;
int i3 = d3;

Chapter 1 22

11
2/11/2019

3. Control flow
3.1. If statement
if (<boolean_exp>)
<true_statement>
[else if (<boolean_exp>)
<else_if_statement>]
[else
<else_statement>]

Chapter 1 23

3. Control flow
3.2. Switch statement

switch (command) {
case 1:
//…
break;
case 2:
//…
break;
default:
//…
break;
}

Chapter 1 24

12
2/11/2019

3. Control flow
3.3. While and Do-While Loops

while (<boolean_expression>)
<loop_body_statement>

do
<loop_body_statement>
while (<boolean_expression>)

Chapter 1 25

3. Control flow
3.4. For Loop
for ([<initialization>]; [<condition>]; [<increment>])
<body_statement>

3.5. Break and Continue Statements


int sum = 0;
while(true){
int x;
cin >>x;
if (x<0) break;
sum +=x
}
cout << “Sum is ” << x << ‘\n’;

Chapter 1 26

13
2/11/2019

4. Functions
A function is a chunk of code that can be called to perform
some tasks
4.1. Argument Passing
 By value: void f(int value)
 By reference: void f(int &ref)
 Example

void f(int value, int &ref) { int main() {


value++; int cat = 1;
ref++; int dog = 5;
cout << value << ‘\n’; f(cat, dog);
cout << ref << ‘\n’; cout << cat << ‘\n’;
} cout << dog << ‘\n’;
return EXIT_SUCCESS;
}
Chapter 1 27

4. Functions
4.1. Argument Passing
 Constant references as argument
 It is inefficient to pass large structures and classes
arguments by value.
 Constant reference informs the compiler that even
though the argument is being passed by reference, the
function cannot alter its value.
 Arrays are not passed by value
 Example
void someFunction(const Passenger &pass) {
pass.name = “new name”; //ILLEGAL!
}

Chapter 1 28

14
2/11/2019

4. Functions
4.2. Overloading
 means defining functions or operators that have the
same name, but whose depends on types of their
actual arguments.
 Example
void print(int x)
{ cout << x; }
void print(const Passenger &pass) {
cout << pass.name << “ “ << pass.mealPref;
if (pass.isFreqFlyer) {
cout << “ “ << pass.freFlyerNo;
}
}
Chapter 1 29

4. Functions
4.2. Overloading
 Operator Overloading: C++ also allows overloading of
operators, such as +, -, +=, and <<.
 Example
bool operator==(const Passenger &x, const Passenger &y) {
return x.name == y.name
&& x.mealPref == y.mealPref
&& x.isFreqFlyer == y.isFreqFlyer
&& x.FreqFlyerNo == y.FreqFlyerNo;
}

Chapter 1 30

15
2/11/2019

Assignment (cont.)
4. Providing that the declareations
int intArray[] = {1,2,3}, *p = intArray;
have been made, what will be the content of intArray
and p after executing

a. *p++

b. (*p)++;

c. *p++; (*p)++;

Chapter 1 31

Assignment (cont.)
5. Using only pointers (no array indexing), write
a. A function to add all numbers in an integer array
b. A function to remove all odd numbers from an
ordered array; the array should remain ordered.
Would it be easier to write this function if the array
were unordered?

Chapter 1 32

16
2/11/2019

5. Classes
Class provides a way to define a new user-defined types,
complete with associated functions and operators
5.1. Class structure
 A class consists of members
 member variables
 member functions
 Access control
class <class_name> {
private:
//… private members
public:
//… public members
};
Chapter 1 33

5. Classes
5.1. Class structure
 Member functions are also called method
 Example
enum MealType {NO_PREF, REGULAR, LOW_FAT, VEGETARIAN};
class Passenger {
private:
string name;
MealType mealPref;
bool isFreqFlyer;
string freqFlyerNo;
public:
//…
Passenger();
bool isFrequentFlyer() const; //This function will not change
the object contents
void makeFrequentFlyer(const string &newfreqFlyerNo);
//…
}
Chapter 1 34

17
2/11/2019

5. Classes
5.1. Class structure
 Out-of-class Function Definition
 Example
bool Passenger::isFrequentFlyer() const
{return isFreqFlyer; }
void Passenger::makeFrequentFlyer(const string
&newFreqFlyerNo) {
isFreqFlyer = true;
freqFlyerNo = newFreqFlyerNo;
}

Chapter 1 35

5. Classes
5.1. Class structure
 In-class Function Definition
 Example
class Passenger {
private:
string name;
MealType mealPref;
bool isFreqFlyer;
string freqFlyerNo;
public:
//…
bool isFrequentFlyer() const
{return isFreqFlyer; }
void makeFrequentFlyer(const string &newfreqFlyerNo) ) {
isFreqFlyer = true;
freqFlyerNo = newFreqFlyerNo;
}
}

Chapter 1 36

18
2/11/2019

5. Classes
5.2. Constructors and Destructors
 Constructor is a special member function whose task is to
perform such an initialization
 Destructor is a function which is called whenever a class
object goes out of existence.
 Example
class Passenger {
private:
//…
public:
Passenger();
Passenger(const string &nm, MealType mp, string ffn =
“NONE”);
Passenger(const Passenger &pass);
//…
};
Chapter 1 37

5. Classes
5.2. Constructors and Destructors
Passenger::Passenger() {
name = “—NO NAME—”
mealPref = NO_PREF;
isFreqFlyer = false;
freqFlyerNo = “NONE”;
}
Passenger(const string &nm, MealType mPref, string ffn = “NONE”) {
name = nm;
mealPref = mp;
isFreqFlyer = (ffn != “NONE”);
freqFlyerNo = ffn;
}
Passenger::Passenger(const Passenger& pass) {
name = pass.name;
mealPref = pass.mealPref;
isFreqFlyer = pass.isFreqFlyer;
freqFlyerNo =pass.freqFlyerNo;
}

Chapter 1 38

19
2/11/2019

5. Classes
5.2. Constructors and Destructors
 Initializing Class Members with Initializer List
 Initializer list is executed before the body of the
constructor
 Example
Passenger::Passenger(const string &nm, MealType mp,
string ffn): name(mn), mealPref(mp),
isFreqFlyer(ffn!=“NONE”) {
freqFlyerNo = ffn;

Chapter 1 39

5. Classes
5.2. Constructors and Destructors
 Example for Destructor
class Vect {
private:
int* theVect;
int vectSize;
public:
Vect(int size = 10) {
vectSize = size;
theVect = new int[size];
}
//…
~Vect()
{ delete [] theVect}
};

Chapter 1 40

20
2/11/2019

5. Classes
5.3. Classes and Memory Allocation
 Consider the following example
 Vect a(100);
 Vect b = a;
 Vect c;
 c=a
 “Vect b = a” is shallow copy, because only the pointers
are copied, not the underlying array contents

a vector(100)

Chapter 1 41

5. Classes
5.3. Classes and Memory Allocation
 To solve the problem, we allocate memory, and we use the system’s copy
constructor and assignment operator
 Example
Vect::Vect(const Vect &a) {
vectSize = a.vectsize;
theVect = new int[vectSize];
for (int i =0; i < vectSize; i++) {
theVect[i] = a.theVect[i]; }
}

Vect& Vect::operator=(const Vect &a) {


if (this != &a) {
delete [] theVect; //delete old array
vectSize = a.vectSize;
theVect = new int[vectSize]; //allocate a new array of the proper size
for (int i=0; i < vectSize; i++) {
theVect[i] = a.theVect[i]; }
}
return *this; //useful for the chain assignment operator. as in a = b = c
}

Chapter 1 42

21
2/11/2019

5. Classes
5.3. Classes and Memory Allocation
 Every class that allocates its own objects using new
should:
 Define a destructor to free any allocated objects.
 Define a copy constructor, which allocates its own
new member storage and copies the contents of member
variables
 Define an assignment constructor, which deallocates
old storage, allocates new storage, and copies all
member variables.

Chapter 1 43

5. Classes
5.4. Class Friends and Class Members
 We can declare a function as a friend, which means that
this function may access the class’s private data.
 Example
class SomeClass {
private:
int secret;
public:
//…
friend ostream& operator << (ostream &out, const
SomeClass &x); //give << operator access to secret
};

ostream& operator<<(ostream &out, const SomeClass &x)


{ cout << x.secret; }

Chapter 1 44

22
2/11/2019

5. Classes
5.4. Class Friends and Class Members
class Matrix;
class Vector {
private:
double coord[3];
public:
//…
friend class Matrix;
};
class Matrix {
private:
double a[3][3];
public:
//…
Vector multiplyBy(const Vector& 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];
return w;
}
};

Chapter 1 45

5. Classes
5.4. Class Friends and Class Members
 Nesting class and types within class
 Example
class Complex {
private:
class Node {
//…
};
//…
};

Chapter 1 46

23
2/11/2019

5. Classes
5.5. The Standard Template Library (STL)
 STL is a collection of useful classes for common data
structures
 string container with characters
 stack container with last-in, first-out access
 queue container with first-in, first-out access
 deque double-ended queue
 vector Resizable array
 list doubly linked list
 priority_queue queue ordered by value
 set container of distinct objects
 map associative array (dictionary)
 Declare libraries:
 #include <iostream>
 #include <string>

Chapter 1 47

5. Classes
5.5. The Standard Template Library (STL)
 Specify type of the object being stored in the container
in <…>
 Example
#include <vector>
vector<int> score(100);
vector<char> buffer(500);
vector<Passenger> passenList(20);

 Advantages of vector:
 check size by size() function
 resize by resize() function
 vector object can be assigned to another

Chapter 1 48

24
2/11/2019

6. Object-Oriented Design
Presentation Assignment

 Group of 3 students
 Content of presentation
 Inheritance (at least 5 slides)
 Polymorphism (at least 5 slides)
 Template (at least 5 slides)
 Requirements
 Definition
 Examples (at least 2 examples)
 Explanation

Chapter 1 49

Homework
1. What are the contents of string S after executing the following
statements
string s = “abc”;
string t = “cde”;
s += s + t[1] + s;

2. Consider the following attempt to allocate a 10-element array


of pointers to doubles and initialize the associated double
values to 0.0. Rewrite the following incorrect code
double* dp[10];
for (int i=0; i<10; i++) dp[i] = 0.0;

3. Write a C++ function printArray(A, m ,n) that prints an mn


two dimensional array A of integers, declared to be “int** A”, to
the standard output. Each of the m rows should appear on
separate line

Chapter 1 50

25
2/11/2019

Homework
4. What is different about the behavior of the following two function f()
and g() which increment a variable and print its value?
void f(int x)
{ std::cout << ++x;}
voidf(int& x)
{ std::cout << ++x;}
5. Write a short C++ function, isMultiple(), that takes two long values,
n and m, and returns true if and only if n is multiple of m, that is,
n=m*i for some integer i.
6. Write a short C++ function, isTwoPower(), that takes and int i and
returns true if and only if i is a power of 2. Do not use multiplication
or division, however.
7. Write a short C++ function that takes an integer n and returns the
sum of all the integers smaller than n.
8. Write a short C++ program that prints its own source code when
executed but does not perform any input or file reading.

Chapter 1 51

26

Das könnte Ihnen auch gefallen