Preliminaries
Linux Basics
- Change Password:
passwd
- shutdown:
sudo shutdown -h 3
(broadcast to all users in 3 mins) - reboot:
sudo reboot -r now
- create an empty file:
touch file-name
- Display file contents:
cat/more/less/head/tail file-name
- find name of current directory:
pwd
Command-line Arguments
Access argv and envp in the main routine
int main(int argc, char **argv, char **envp)
argc
: Number of arguments in the listenvp
: Shell reads in environment variables into envp list; can be omitted if not needed
Compilation and multiple-file projects
options for g++
-o filename
: specify the output filename-E
: Stop after the preprocessing stage (只进行预编译)-S
: Stop before assembling (生成汇编代码,不进行汇编)-c
: do not run the linker (不进行链接)
Declaration
A function (函数) or variable (变量) can be defined only once, but can be declared many times.
- Variable declaration:
extern int x;
- Function declaration:
extern void sum (int argc, char* argv[]);
Include Header Files
-
Preprocessor directive (预编译命令)
#include
- Angle brackets
<>
: typically for system headers - Double quotes
" "
: First search in current directory where the compilation is launched
Suggestion: include related header files in all the source files, wherever the declared functions are either defined or referenced (引用).
- Angle brackets
Makefile
Separate Compilation
-
Different source files (.cpp) (源文件) are compiled separately into different relocatable object files(.o or obj) (可重定位的目标文件)
g++ -c main.cpp -o main.o
-
The relocatable object files are linked into the executable object file (可执行目标文件) by a tool called linker (链接器)
g++ main.o sum.o product.o -o test.exe
make and Makefile
A tool called make is introduced to manage the compilation process.
- Dependency rule (依赖规则)
- Defined by comparing the modification dates of the source/header files (比较文件的更新日期)
- When a dependency rule is satisfied, the corresponding (compilation/linking) commands will be executed.
test.exe: product.cpp sum.cpp main.cpp functions.h
g++ product.cpp sum.cpp main.cpp -o test.exe
Dependency rule: if test.exe does not exist or is older than any of the files after the colon(😃, the following command (g++ …) will be executed.
an example:
test.exe: product.o sum.o main.o
g++ product.o sum.o main.o -o test.exe
product.o: product.cpp functions.h
g++ -c product.cpp -o product.o
sum.o: sum.cpp functions.h
g++ -c sum.cpp -o sum.o
main.o: main.cpp functions.h
g++ -c main.cpp -o main.o
More on Makefile
- Default target is all
- If one specific target is needed:
make test1.exe
There are tools for automatically generating the makefile, such as cmake.
Library
Static library (Linux)
A particular file of archive format (with .a suffix), which is a collection of concatenated relocatable object files, with a header describing the size and location of each object file.
g++ -static main.o test.a -o test.out
g++ -static main.o -L. -ltest -o test.out
-static: tells the linker to build a fully linked executable object file without any further linking at load time
Shared Library
An object module (with .so suffix) loaded at an arbitrary memory address (内存地址) and linked with a program in memory, at either run time (运行期) or load time (启动期). This is called dynamic linking (动态链接)
g++ -c -fPIC sum.cxx -o sum.o
g++ -shared -o libtest.so product.o sum.o
Class
variables and function are encapsulated (封装) into a structure called class.
Key features of OOP:
- Abstraction (抽象)
- Encapsulation (封装) (information hiding)
- Inheritance (继承)
- Polymorphism (多态)
Object & Abstraction
Member Variable and Member Function
class Bird{
public:
void fly();
void sing();
void eat(); //Member Functions
private:
std::string name_;
std::string color_;
float weight_;
float height_; //Member Variables
};
Access Control to Class Members
-
Do not restrict class designers (设计者)
-
Restrict class users (使用者)
Example:
ClassName objectName; objectName.memberVariable = XX; //should be restricted objectName.memberFunction(YY); //without restrict
Public Members
- accessible from objects by class users
- the interface (接口) between class designers and the class users
- When no keyword is given
- Default access control for class is private
- Default access control for struct is public
Private Members
- only accessible within member functions by class designers
- This enables the information hiding (信息隐藏) for the class designers
Protected Members
- Similar access control to
private
- Different from
private
for the derived classes- Used in inheritance (继承)
Definition of Member Functions
Member function
- Declared inside the class definition (类声明内部)
- Typically defined outside the class definition
- With scope resolution operator
::
- With scope resolution operator
Inline function
Functions less than 10 lines can be declared inline to improve efficiency
#ifndef BIRD_H_
#define BIRD_H_ //Preprocessor directive
#include <iostream>
#include <string>
class Bird {
public:
void setSpeed(float speed) {
speed_ = speed;
}//inline functions
private:
float speed_;
};
#endif
#include "bird.h"
using namespace std;
void Bird::fly(float time) {
float distance = speed_ * time;
cout << name_ << " flies distance: " << distance << endl;
}
Encapsulation
-
Integrate attribute and behavior into an entity
-
Improve safety
- Set different access control (访问权限控制) for different members.
- Class users can only access public members (also called interfaces, 接口)
-
Decouple (解耦) between class users and designers
this Pointer
-
Keyword
this
: points to the address(地址) of the current object. -
Usage
Return current object’s address from its member functions
- Typically used in operator overloading(e.g.,
=
):return *this;
- Typically used in operator overloading(e.g.,
class Bird {
public:
void fly(float time);
Bird* setName(char *name) {
name_ = name;
return this;
}
private:
std::string name_;
};
//User program:
Bird b;
b.setName(“Eagle")‐>fly(10.0);
Constructor (构造函数)
Lifetime (生命期) or scope (作用域) of objects
Constructor (ctor, 构造函数) and destructor (dtor, 析构函数) are introduced for better SAFETY (安全性)
-
Special member functions for initialization (初始化) and cleanup (清除).
-
Automatically called by the compiler (编译器) when an object is being created (创建) or deleted (销毁)
-
Constructors and destructor are typically
public
call constructor/destructor by
new/delete
Why constructor is necessary?
Constructor provides a place to ensure certain task be executed, such as member initialization, along with object creation (对象创建时进行初始化)
Avoids the careless/wrong usage of a class
Constructor is automatically called by the compiler when the object is being created for definition of an object:
ClassA a; //Stack object
ClassA *pA = new ClassA; //Heap object
-
Constructors have the same name as the class
-
Parameters can be provided in constructor for initialization
class Tree { int height_; public: Tree() { height_ = 0; } // Constructor 1 Tree(int h) { height_ = h; } // Constructor 2 };
Default Constructor
a special constructor without function arguments (above. Constructor 1)
When no constructor is defined in a class, the compiler will synthesize (合成) a default constructor, called a default default constructor
Using default keyword for Default Constructor
The use of the default
keyword is preferred in modern C++ code
class Tree {
int height_{0};
public:
Tree() = default; //equals to Tree(){}
};
Member Initializer List
class Tree {
int height_ {0}, year_ {0};
public:
Tree(int h, int y) : year_{y}, height_{h} { }
};
enjoys better efficiency
Keyword explicit
Single-parameter constructor enables the implicit type conversion (隐式类型转换)
To forbid such conversions, use keyword explicit
.
class Tree {
int height_{0};
public:
Tree(int h):height_{h} {}
//explicit Tree(int h):height_{h} {}
}; //…
void foo(Tree t){
//…
}
foo(5); //works if no explicit keyword, error if explicit is used
Delegating Constructor
Depends on other constructors for the initialization
class Tree {
int height_, size_;
public:
Tree(int h) : height_{h} { }
Tree() : Tree {h} { size_ = 0; }//Delegating constructor
};
Destructor (析构函数)
Clean up the resource (memory) occupied by the object. A special function called destructor(prepare-to-die) is introduced for cleanup.
Destructor is automatically called by compiler when:
- An object goes out of its scope
- Using
delete
:ClassA *pA = new ClassA; delete pA;
- In modern C++, we can use
std::unique_ptr<>
andstd::shared_ptr<>
instead ofnew
anddelete
.
DON’T explicitly call (显式调用) the destructor unless necessary.
pA->~ClassA(); // works but NOT recommended
- Destructor
- Name of destructor is the same as the class, preceded by
~
- No function parameters
- There should be only one destructor
- The destructor needs to be public to be automatically called
- Name of destructor is the same as the class, preceded by
When is a destructor necessary?
- To free (释放) member variables allocated on the heap (堆)
- Free other occupied resources (socket, printer, etc.)
Default Keyword
the same as previous
Stack vs. Heap Variables
-
Stack (栈) and Heap (堆) are memory (内存) fragments for storing the variables of the program.
-
Stack
- Limited size of several kilobytes (千字节) to megabytes (兆) depending on the system (系统) and compiler settings.
- Store local variables of different functions
- Example of variables on stack:
int i; double val; ClassA a;
- **Stack overflow (栈溢出) **may occur for large array variables (e.g.,
int a[100000000];
) and deep recursive functions (递归函数)
-
Heap
-
The size of heap is much larger than stack: so large array variables(数组变量)should be defined on heap
-
How to define variables on the heap?
int num = 1000000; // on stack int *arr = new int[num]; delete []arr; // on heap int *arr = (int*)malloc(sizeof(int)*num); free(arr); // on heap
-