Beruflich Dokumente
Kultur Dokumente
Chapter 1 1
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;
}
1
2/11/2019
Chapter 1 3
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
Correct or wrong
char newline = ‘\n’;
unsigned short s = 100000;
long BIGnumber = 314159265L;
double t = 3.14E5
Chapter 1 5
Chapter 1 6
3
2/11/2019
Chapter 1 7
Chapter 1 8
4
2/11/2019
Chapter 1 9
5
2/11/2019
Chapter 1 12
6
2/11/2019
int main() {
const int cat = 2;
cout << cat;
return EXIT_SUCCESS;
}
Chapter 1 13
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:
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
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>
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
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]; }
}
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
};
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;
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