#include <iostream>
using namespace std;
/*
由己存在的对象,创建新对象。也就是说新对象,不由构造器来构造,而是由
拷贝 构造器来完成。拷贝构造器的格式是固定的。
*/
class Test{
private:
int m_x;
int m_y;
public:
//无参数的构造函数
Test() {
m_x = 0;
m_y = 0;
cout << "调用了无参数的构造函数" << endl;
}
//拷贝构造函数 ,想通过另一个Test对象 another 将本对象进行拷贝
Test(const Test& another){
m_x = another.m_x;
m_y = another.m_y;
cout << "调用了拷贝构造函数" << endl;
}
//等号操作符
void operator = (const Test& t){
m_x = t.m_x;
m_y = t.m_y;
cout << "调用了等号操作符" << endl;
}
void printT(){
cout << "x : " << m_x << ", y : " << m_y << endl;
}
//提供一个析构函数
~Test(){
}
};
int main(void){
cout << "-------t1和t2被创建--------" << endl;
Test t2;
Test t1(t2); //调用t3的拷贝构造函数 //调用拷贝构造函数的方式
t1.printT();
cout << "---------------" << endl;
cout << "-------t4被创建--------" << endl;
Test t4 = t2; // 依然是调用t4的拷贝构造函数,
cout << "---------------" << endl;
cout << "-------t5被创建--------" << endl;
Test t5; //先调用无惨构造。
t5 = t2; //不会调用拷贝构造函数 //调用=号重载操作符 赋值操作符
}
注:当没有声明拷贝构造函数时,会自动调用默认的拷贝构造函数。