深入C++中构造函数、拷贝构造函数、赋值操作符、析构函数的调用过程总结
2015-10-05 16:53
671 查看
用同一个类的源对象构造一个目标对象时,会调用拷贝构造函数来构造目标对象,如果没有定义拷贝构造函数,将调用类的默认拷贝函数来构造目标对象
当一个函数的返回值为一个类的对象时,如果在调用函数中,没有定义一个对象来接收这个返回对象值,会用返回一个临时对象保存返回对象的值。在被调用函数结束时,这个临时对象被销毁。而当调用函数中有一个接受对象时,就将返回对象赋值给接收对象,这个返回对象在调用函数结束时调用析构函数
当类有一个带有一个参数的构造函数时,可以用这个参数同类型的数据初始化这个对象,默认会调用这个构造函数
先看一段代码:
运行结果:
结果分析:
Constructor is called.1 //用1构造参数b
Copy Constructor is called.1 //用b拷贝构造一个临时对象,因为此时没有对象来接受fun的返回值
Destructor is called. 1 //参数b被析构
Destructor is called. 1 //临时对象被析构
Constructor is called.2 //用2构造参数b
Copy Constructor is called.2 //用b拷贝构造t1,此时调用的是拷贝构造函数
Destructor is called. 2 //参数b被析构
Default constructor is called 0. //调用默认的构造函数构造t2
Constructor is called.3 //用3构造参数b
Copy Constructor is called.3 //用b拷贝构造一个临时对象
Destructor is called. 3 //参数b被析构
The operator "= " is called.3 //调用=操作符初始化t2,此时调用的是赋值操作符
Destructor is called. 3 //临时对象被析构
Destructor is called. 3 //t2被析构
Destructor is called. 2 //t1被析构
当一个函数的返回值为一个类的对象时,如果在调用函数中,没有定义一个对象来接收这个返回对象值,会用返回一个临时对象保存返回对象的值。在被调用函数结束时,这个临时对象被销毁。而当调用函数中有一个接受对象时,就将返回对象赋值给接收对象,这个返回对象在调用函数结束时调用析构函数
当类有一个带有一个参数的构造函数时,可以用这个参数同类型的数据初始化这个对象,默认会调用这个构造函数
先看一段代码:
class B { public: B():data(0) { cout << "Default constructor is called." <<data<< endl; } B(int i):data(i) //例如:B b = 10;这就隐式调用只有一个参数的构造函数 { cout << "Construtor is called." <<data<<endl; } B(B& b) { data = b.data; cout << "Copy construtor is called."<<data<<endl; } B& operator = (const B&b) { this->data = b.data; cout << "The operator is called."<<data<<endl; return *this; } ~B() { cout << "Destrutor is called."<<data<<endl; } private: int data; }; B fun(B b) //函数,参数是一个B类型对象,返回值也是一个B类型的对象 { return b; } void main() { fun(1); cout << endl; B t1 = fun(2); //这种形式,调用拷贝构造函数 cout << endl; B t2; //先定义的B对象 t2 t2 = fun(3); //然后给 对象t2 赋值,这种形式调用重载的 “=” }
运行结果:
结果分析:
Constructor is called.1 //用1构造参数b
Copy Constructor is called.1 //用b拷贝构造一个临时对象,因为此时没有对象来接受fun的返回值
Destructor is called. 1 //参数b被析构
Destructor is called. 1 //临时对象被析构
Constructor is called.2 //用2构造参数b
Copy Constructor is called.2 //用b拷贝构造t1,此时调用的是拷贝构造函数
Destructor is called. 2 //参数b被析构
Default constructor is called 0. //调用默认的构造函数构造t2
Constructor is called.3 //用3构造参数b
Copy Constructor is called.3 //用b拷贝构造一个临时对象
Destructor is called. 3 //参数b被析构
The operator "= " is called.3 //调用=操作符初始化t2,此时调用的是赋值操作符
Destructor is called. 3 //临时对象被析构
Destructor is called. 3 //t2被析构
Destructor is called. 2 //t1被析构