默认构造函数 Default Constructors
- Default constructor: a constructor which can be called without arguments
- 不使用任何外部传入的参数argument,而不是parameter
If you define no constructors, the compiler automatically provide one
- 如果没有构造函数,编译器会默认给我们构造一个默认构造函数,既无参数,函数体也是空的
MyTime::MyTime(){}
- 如果没有构造函数,编译器会默认给我们构造一个默认构造函数,既无参数,函数体也是空的
If you define constructors, the compiler will not generate a default one.
- 如果构建了任意的一个构造函数,编译器不会再生成一个构造函数 ```cpp class MyTime { public: MyTime(int n){ … } };
MyTime mt; //no appropriate constructor
上述代码中,人为的定义了一个带参的构造函数,编译器也不会生成默认的构造函数,这时如果我们要创建对象,就需要调用默认构造函数,所以该程序再编译的时候报错。
- To avoid ambiguous
```cpp
class MyTime
{
public: //two default constructors
MyTime(){ ... }
MyTime(int n = 0){ ... }
};
MyTime mt; //which constructor?、
// 程序不知道该调用哪一个构造函数,编译时会报错。
析构函数
Implicitly-defined Destructor 隐式被定义的析构函数
If no destructor is defined, the compiler will generate an empty one.
MyTime::~MyTime(){}
Memory allocated in constructors is normally released in a destructor.
一般会把内存资源的释放放在析构函数中,编译器自动生成的析构函数时不会执行任何操作的,并不能释放资源。
Default Copy Constructors 默认复制构造函数
- A copy constructor. Only one parameter, or the rest have default values
- 拷贝的构造函数, ```cpp MyTime::MyTime(MyTime & t){ … }
MyTime t1(1, 59); MyTime t2(t1); //copy constructor MyTime t3 = t1; //copy constructor
- Default copy constructor:
- If no user-defined copy constructors, the compiler will generate one.
- Copy all non-static data members.
- 编译器会把这个对象的所有非静态的成员全部拷贝一遍。
<a name="EuiVH"></a>
## Default Copy Assignment
- Assignment operators: =, +=, -=, ...
- Copy assignment operator
```cpp
MyTime & MyTime::operator=(MyTime & ){...}
MyTime t1(1, 59);
MyTime t2 = t1; //copy constructor 构造操作
t2 = t1; //copy assignment 赋值操作
- Default copy assignment operator
- If no user-defined copy assignment constructors, the compiler will generate one.
- Copy all non-static data members.