Fundamental C++ Knowledge

slide 02 __Elementary Programming

Identifiers


Identifiers (標識符) are used to name variables, functions, and other things in a program. An identifier is a sequence of characters comprising letters, underscores ( _ ) and digits. An identifier must start with a letter or an underscore; An identifier can be of any length, but your C++ compiler may impose restriction. Use identifiers of 31 characters or fewer to ensure portability.
 

Expression & Syntax


Expressions below are all correct.

cout<< (x = 1);
i = j = k = 1;
int i = j = k = 1; //this is incorrect, fragrant!
int i; int i; //incorrect, fragrant!

Here is the syntax for declaring a constant : A constant must be declared and initialized in the same statement.

====~~const datatype CONSTANTNAME = value;~~====
const double PI = 3.14159;
const double SIZE = 1

 

Usages


  • Find the capacity of a datatype.
cout << "INT_MAX is " << INT_MAX << endl;
cout << "LONG_MAX is " << LONG_MAX << endl;
cout << "FLT_MIN is " << FLT_MIN << endl;
cout << "DBL_MIN is " << DBL_MIN << endl;
  • The pow(a, b) function can be used to compute ab ,which is a function defined in the cmath library.

  • You can use the sizeof() function to find the size of a type or a variable (bytes).

Summarize

  • Increment && Decrement
Operator Name Description
++var preincrement Increment var by 1 and use the new var value in the statement.
var++ postincrement Increment var by 1, but use the original var value in the statement.
- -var predecrement Decrement var by 1 and use the new var value in the statement.
var- - postdecrement Decrement var by 1 and use the original var value in the statement.
  • Type Conversion
//(type narrowing)
int i = 5.4; //i is 5
//(type widening) 
double f = i; //f is 5.0 
double g = 5.4;
//(type narrowing)
int j = g; //j is 5

int i = static_cast<int>(5.4);
int i = (int)5.

 

Slide 0304 __Selections & Functions

Magic functions


Generating Random Number

#include <cstdlib>
#include <ctime>
	srand(time(0));
	int i = rand();

 
Trigonometric Functions

Function Description
sin(radians) Returns the trigonometric sine of an angle in radians.
cos(radians) Returns the trigonometric cosine of an angle in radians.
tan(radians) Returns the trigonometric tangent of an angle in radians.
asin(a) Returns the angle in radians for the inverse of sine.
acos(a) Returns the angle in radians for the inverse of cosine.
atan(a) Returns the angle in radians for the inverse of tangent.

 
Exponent Functions

Function Description
exp(x) Returns e raised to power of x (ex).
log(x) Returns the natural logarithm of x (ln(x) = loge(x)).
log10(x) Returns the base 10 logarithm of x (log10(x)).
pow(a, b) Returns a raised to the power of b (ab).
sqrt(x) Returns the square root of x for x > = 0.

 
Rounding Functions

Function Description
ceil(x) x is rounded up to its nearest integer. This integer is returned as a double value.
floor(x) x is rounded down to its nearest integer. This integer is returned as a double value.

 
Other Functions

double fmod (double numer , double denom);

//fmod of 5.3 / 2 is 1.300000 
//fmod of 18.5 / 4.2 is 1.700000

 

Character Data Type


Escape Sequences for Special Character

Escape Sequence Name ASCII Code
\b Backspace 8
\t Tab 9
\n Linefeed 10
\f Formfeed 12
\r Carriage Return 13
\ Backslash 92
Single Quote 39
\” Double Quote 34
cout << sizeof('A' + '!') << endl; //4

 

Others


Switch Statements

switch (switch-expression){
	case value1: statement(s)1;
		break;
	case value2: statement(s)2;
		break;
	...
	case valueN: statement(s)N;
		break;
	default: statement(s)-for-default;
} 

 
Formatting Output

cout << fixed << setprecision(2) << 232123434.357 << endl;
cout << setprecision(6);
cout << 1.23 << endl;
cout << showpoint << 1.23 << endl;
float a = 123;
cout << a << endl;
cout << setw(8) << "C++" << setw(6) << 101 << endl;

Output:
232123434.36
1.23
1.23000
123.000
C++ 101

 

Slide 06 __Functions

 

A Legal Function


void t1(int x, int y = 0, int z); // Illegal
void t2(int x = 0, int y = 0, int z); // Illegal
void t3(int x, int y = 0, int z = 0); // Legal
void t4(int x = 0, int y = 0, int z = 0); // Legal

 

Inline !


C++ provides inline functions to avoid function calls. To specify an inline function, precede the function declaration with the inline keyword.

inline void f(int m, int y) {
	cout << "month is " << m << endl; 
	cout << "year is " << y << endl;
}
int main() {
	int m = 10, int y = 2018;
	f(m, y);
	f(11, 2017);
	return 0;
}

 

Constant Reference Parameters


If your program uses a pass-by-reference parameter and the parameter is not changed in the function, you should mark it constant to tell the compiler that the parameter should not be changed.
To do so, place the const keyword before the parameter in the
function declaration.

int max(const int& num1, const int& num2){
	int result;
	if (num1 > num2)
		result = num1;
	else result = num2;
	
	return result;
}

 

Local, Global and Static Variables


Local variable:
  Inside a functionGlobal .
variable:
  Outside all functionsSame name ::y.
Static Local Variables
After a function completes its execution, all its local variables are destroyed. Sometimes it is desirable to retain the values stored in local variables so that they can be used in the next call.
C++ allows you to declare static local variables. Static local variables are permanently allocated in the memory for the lifetime of the program. To declare a static variable, use the keyword static.

#include <iostream>
using namespace std; 
void t1();
int main() {
	t1();
	t1();
	return 0; 
}
void t1(){
	static int x = 1;
	int y = 1; 
	x++;
	y++;
	cout << "x is " << x << endl;
	cout << "y is " << y << endl;
}

Output:
    x is 2
    y is 2
    x is 3
    y is 2

 

Slide 0708 __Arrays & C-String

 

Array


Array Initializers
  C++ allows you to initialize a part of the array.
  For example, the following statement assigns values 3.14 to the first element of the array. The other two elements will be set to
zero.

double myArray[3] = {3.14}; 
double myArray[] = {3.14, 0, 0}; 
double myArray[3] = {3.14, 0, 0};
//all above are the same

Known Size

const int ARRAY_SIZE = 10;
double myList[ARRAY_SIZE];

 

Passing Arrays to Functions


  When an array argument is passed to a function, its starting address is passed to the array parameter in the function. Both parameter and argument refer to the same array.

void printArray(int [], int);
void doubleArray(int [], int);
int main() {
	int numbers[5] = {1, 4, 3, 6, 8};
	doubleArray(numbers, 5); // Invoke the function
	PrintArray(numbers, 5); // Invoke the function
	return 0;
}
void PrintArray(int list[], int arraySize) {
	for (int i = 0; i < arraySize; i++)
		cout << list[i] << " ";
}	
void doubleArray(int list[], int arraySize) {
	for (int i = 0; i < arraySize; i++)
		list[i] *= 2;
} 

Output
    2 8 6 12 16

  Normally when you pass an array to a function, you should also pass its size in another argument, so that the function knows how many elements are in the array.
 

Const array parameter


void p(const int list[], int arraySize);
p(list, size);

 

Prevent Changes of Array Arguments in Functions


  You can define const array parameter in a function to prevent it from being changed in a function.
  Passing an array merely passes the starting memory address of the array. The array elements are not copied. This makes sense for conserving memory space. However, using array arguments could lead to errors if your function accidentally changed the array.
  To prevent this, you can put the const keyword before the array parameter to tell the compiler that the array cannot be changed. The compiler will report errors if the code in the function attempts to modify the array

void function(const int n[], int size)
{
}

Error !

int[] reverse (const int list[], int size) //error

 

C-String Functions


Function Description
int strlen(char *s1) Returns the length of the string, i.e., the number of the characters before the null terminator.
char *strcpy(char *s1, const char *s2) Copies string s2 to string s1.
char *strncpy(char *s1, const char *s2, size_t n) Copies the first n characters from string s2 to string s1.
char *strcat(char *s1, const char *s2) Appends string s2 to s1.
char *strncat(char *s1, const char *s2, size_t n) Appends the first n characters from string s2 to s1.
int *strcmp(char *s1, const char *s2) Returns a value greater than 0, 0, or less than 0 if s1 is greater than, equal to, or less than s2 based on the numeric code of the characters.
int *strncmp(char *s1, const char *s2, size_t n) Same as strcmp, but compares up to n number of characters in s1 with those in s2.
int atoi(char *s1) Returns an int value for the string.
double atof(char *s1) Returns a double value for the string.
long atol(char *s1) Returns a long value for the string.
void itoa(int value, char *s1, int radix) Obtains an integer value to a string based on specified radix.

All these functions are defined in the cstring header file except that conversion functions atoi, atof, atol, and itoa are defined in the cstdlib function.
 

Multidimensional Arrays


Declaring and Assigning Two-Dimensional Arrays

int matrix[4][3] = {
	{1, 2, 3},{4, 5, 6},{7, 8, 9},{10, 11, 12}
};
//Equivalent
int matrix[][3] = {
	{1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12}
};

int matrix[4][3] = {
	{1, 2, 3}, {4, 5, 6}, {7, 8, 9}
};
//Equivalent
int matrix[4][3] = {
	{1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {0, 0, 0}
};

 
Passing Two-dimensional Arrays to Functions
When passing a two-dimensional array to a function,
C++ requires that the column size be specified in
the function parameter type declaration.

int sum(const int a[][4], int rowSize) {
}
int main() {
	int m[rowSize][4];
	cout << "Sum is " << sum(m, rowSize) << endl;
	return 0;
}

 

Slide 09 __Class

Defining Classes For Objects


Class : data fields + functions
   (normal functions + constructors)

//Example;
class Circle{
	public:// The radius of this circle
		double radius;// Construct a circle object
	Circle() {
		radius = 1;
	}// Construct a circle object
	Circle(double newRadius) {
		radius = newRadius;
	}// Return the area of this circle
	double getArea() {
		return radius * radius * 3.14159;
	}
};

 
Constructors
Constructors are a special kind of function, with three peculiarities:

  • Constructors must have the same name as the class itself.
  • Constructors do NOT have a return type—not even void.
  • Constructors are invoked when an object is created.
  • As a class member, a data field cannot be initialized when it is declared.
public:
	double radius = 5.0;//Error!

 
Note: Like regular functions, constructors can be overloaded, making it easy to construct objects with different sets of data values.
  A class may be defined without constructors. In this case, a no-arg constructor with an empty body is implicitly defined in the class. Called a default constructor, it is provided automatically only if no constructors are explicitly defined in the classes.
 

Anonymous Objects


Occasionally you may create an object and use it only once. In this case, you dont have to name it. Such objects are called Anonymous Objects.

ClassName()
	circle1 = Circle();//using the no-arg constructor
ClassName(arguments)
	circle1 = Circle(5);//using the constructor with arguments

//Example
cout << "Area is " << Circle().getArea() << endl;
cout << "Area is " << Circle(5).getArea() << endl;

 

Separating Class Definition from Class Implementation


C++ allows you to separate class definition from implementation. The class definition and implementation may be in two separate files.

Class Definition Describing the contract of the class.
name.h Listing all the data fields, constructor prototypes and function prototypes.
Class Implementation Carrying out the contract of the class.
name.cpp Implementing the constructors and functions.

在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述
 
Prevent Multiple Inclusion
在這裏插入圖片描述
The C++ #ifndef directive along with the #define directive can be used to prevent a header file from being included multiple times. This is known as inclusion guard. To make this work, you have to add three lines to the header file.

#ifndef CLASSNAME_H
#define CLASSNAME_H
class ClassName{};
#endif

 

Inline Functions in Classes


You can define short functions as inline functions in a class to improve performance.

  1. When a function is implemented inside a class definition, it automatically becomes an inline function.
 class A {
 	public:A(){}
 	double f1() {
 		return 1.0;
 	}
 	double f2();
  1. There is another way to define inline functions for classes. You may define inline functions in the class’s implementation file.
inline double A::f1() {
   return 1.0;
}

      

Slide 10 __Object-Oriented Thinking

Stringstream


To conver a number to a string, a simple approach is to use the stringstream class in the <sstream> header. Stringstream provides an interface to manipulate strings as if they were input/output streams. One application of stringstream is for converting numbers to strings.

#include <sstream>
stringstream ss;
ss << 3.1415;
string s = ss.str();

Converting Numbers to Strings

stringstream ss;
ss << 3.1415;
string s = ss.str(); // s is "3.1415"
cout << s[1] << endl; // '.'
cout << s.size() << endl; //6

 
Splitting Strings

string text("Programming is fun");
stringstream ss(text);
cout << "The words in the text are: " << endl;
string word;
while (!ss.eof()) {
	ss >> word;
	cout << word << endl;
}

Output:
   The words in the text are:
   Programming
   is
   fun

 

Passing Objects to Functions


Objects can be passed to a function by value or by reference, but it is more efficient to pass objects by reference.

void printCircle(Circle& c){
	cout << "r is " << c.getRadius() << endl;
}

int main() {
	Circle myCircle(5.0);
	printCircle(myCircle);
	return 0;
}

 

Instant and Static Members


A static variable is shared by all objects of the class. A static function CANNOT access instance members of the class.
在這裏插入圖片描述
在這裏插入圖片描述
Tip: Use class name.
  Use className::functionName(arguments) to invoke a static function, because the user can easily recognize the static function in the class.

	cout << Circle::getNumberOfObjects() << endl;

 

Constant Member Functions


C++ also enables you to specify a constant member function to tell the compiler that the function should NOT change the value of any data fields in the object.
Syntax: place the const keyword at the end of the function header.
在這裏插入圖片描述
 

Object Composition


An object can contain another object. The relationship between the two is called composition.
Composition is actually a special case of the aggregation relationship. Aggregation models has-a relationships and represents an ownership relationship between two objects.
在這裏插入圖片描述
在這裏插入圖片描述
 

Class Design Guidelines

  1. Cohesion
  2. Consistency
  3. Encapsulation
  4. Clarity
  5. Completeness
  6. Instance vs. Static

 

Slide 11 __Pointer

在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述
THX my little princess zzy~ This is an article on pointer!
       

Slide 12 __Templates

Templates Basic


Templates functions and classes enable programs to work on many different data types without being rewritten for each one.
To define a template function for finding a maximum value between two values of a generic type:

template<typename T> //before a function
T maxValue(T a, T b) {
	if (a > b)
		return a;
	else
		return b;
}

The definition for the function template begins with the keyword template followed by a list of parameters. Each parameter must be preceded by the interchangeable keyword typename or class in the form < typename typeParameter > or < class typeParameter >.
在這裏插入圖片描述

Note: Occasionally, a template function may have more than one parameter. In this case, place the parameters together inside the brackets, separated by commas, such as:
   <typename T1, typename T2, typename T3>
 

Class Templates


  1. Combine class definition and class
    implementation into one file.
  2. For definition:
    a. Place the template prefix before the class definition.
    b. The type parameter can be used in the class just like any regular data type.
  3. For implementation:
    a. Place the template prefix before the constructor and function header in the implementation
    .b. Class name before the scope resolution operator :: is
    ClassName< T >.
//Definition
///stack.h
template <typename T>
class Stack{
	public:
		Stack();
		bool isEmpty() 	const;
		T peek() const;
		void push(T value);
		T pop();
		int getSize() const;
		void display() const;
	private:
		T elements[100];
		int size;
};
//Implementation
template<typename T>
Stack<T>::Stack(){
	size = 0;
}
template<typename T>
T Stack<T>::peek() const {
	return elements[size-1];
}
template<typename T>
void Stack<T>::push(T value){
	elements[size ++] = value;
}

 

Slide 13 __Inheritance and Polymorphism

The three pillars of object-oriented programming are Encapsulation, Inheritance, and polymorphism.


Inheritance


The class definition for Circle defines that the Circle class is derived from the base class GeometricObject.
The syntax:

class Circle: public GeometricObject

public keyword: all public members in GeometricObject are
inherited in Circle.
 
Generic Programming
An object of a derived class can be passed wherever an object of a base type parameter is required. Thus a function can be used generically for a wide range of object arguments. This is known as generic programming.
在這裏插入圖片描述
  

Constructors & Destructors


The constructor of a derived class first calls its base class’s constructor before it executes its own code. The destructor of a derived class executes its own code then automatically calls its base class’s destructor.
You can invoke the base class’s constructor from the constructor initializer list of the derived class. The syntax is as follows:

//Invoking the no-arg constructor of its base class
DerivedClass(parameterList): BaseClass(){
	// Perform initialization
}

//Invoking the base class constructor with the specified arguments
DerivedClass(parameterList): BaseClass(argumentList){
	// Perform initialization
}

If a base constructor is not invoked explicitly, the base class’s no-arg constructor is invoked by defaut.
在這裏插入圖片描述

The Circle(double radius, const string& color, bool filled) constructor can also be implemented by invoking the base class’s constructor GeometricObject(const string& color, bool filled) as follows:

Circle::Circle(double radius, const string& color, bool filled)
: GeometricObject(color, filled), radius(radius){
}

在這裏插入圖片描述
 

Redefining Functions


A function defined in the base class can be redefined in the derived classes.

 

Polymorphism


Polymorphism means that a variable of a supertype
can refer to a subtype object.

The function displayGeometricObject takes a parameter of the
GeometricObject type.

void displayGeometricObject(const GeometricObject& shape) {
	cout << shape.getColor() << endl;
}

You can invoke displayGeometricObject by passing any instance of GeometricObject, Circle, and Rectangle.

int main(){
	displayGeometricObject(GeometricObject("black", true));
	displayGeometricObject(Circle(5));
	displayGeometricObject(Rectangle(2, 3));
	return 0;
}

An object of a derived class can be used wherever
its base class object is used.

 

Virtual Functions & Dynamic Binding


Virtual functions
A function can be implemented in several classes along the inheritance chain. Virtual functions enable the system to decide which function is invoked at runtime based on the actual type of the objects.

void displayGeometricObject(const GeometricObject& shape) {
	cout << shape.toString() << endl;
}

在這裏插入圖片描述
Define the toString() function as virtual in the base class:

virtual string toString() const;

 
Dynamic binding: C++ dynamically binds the implementation of the function at runtime, decided by the actual class of the object referenced by the variables.
To enable dynamic binding for a function, you need to do two
things:

  1. The function must be defined virtual in the base class.
  2. The variable that references the object must be passed by reference or passed as a pointer in the virtual function.
void displayGeometricObject(const GeometricObject& shape) {
	cout << shape.toString() << endl;
}

void displayGeometricObject(const GeometricObject* shape) {
	cout << (*shape).toString() << endl;
}

      

Keyword :  Protected


A protected member of a class can be accessed from
a derived class.
在這裏插入圖片描述

class B{
	public:
		int i;
	protected:
		int j;
	private:
		int k;
};

class A: public B{
	public:
		void display() const{
			cout << i << endl; // Fine
			cout << j << endl; // Fine
			cout << k << endl; // Wrong
		}
};

int main(){
	A a;
	cout << a.i << endl; // Fine 
	cout << a.j << endl; // Wrong
	cout << a.k << endl; // Wrong
	return 0;
}

      

Abstract Classes & Pure Virtual Functions


An abstract class CANNOT be used to create objects. An abstract class contains abstract functions, which are implemented in concrete derived classes.
在這裏插入圖片描述
A pure virtual function is defined this way:
在這裏插入圖片描述
A pure virtual function does not have a body or implementation in the base class.
 
GeometricObject is just like a regular class, except that you cannot create objects from it because it is an abstract class.
在這裏插入圖片描述
This example presents a program that creates two geometric objects (a circle and a rectangle), invokes the equalArea function to check whether the two objects have equal areas:

bool equalArea(const GeometricObject& g1, const GeometricObject& g2) {
	cout << g1.getArea()<< endl;
	cout << g2.getArea()<< endl;
	return g1.getArea() == g2.getArea();
}
int main() {
	Circle circle (5, "red", true);
	Rectangle rect;
	equalArea(circle, rect);
	return 0;
} 

在這裏插入圖片描述
     


Written in the End

Acknowledge Assoc Prof. Qian SUN.
All above are from her slides.
I am just a REPEATER!
^ - ^~


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章