class Test
{
private:
int m_nTest;
public:
Test(int x);
Test(const Test &);
Test& operator =(const Test&);
~Test();
void func(Test temp)
{
}
};
Test :: Test(int x) :m_nTest(x)
{
cout << "带参构造函数" << endl;
}
Test :: Test(const Test &other)
{
m_nTest = other.m_nTest;
cout << "拷贝构造函数" << endl;
}
Test& Test :: operator =(const Test& other)
{
cout << "赋值构造函数" << endl;
if (this == &other)
{
return *this;
}
else
{
m_nTest = other.m_nTest;
}
return *this;
}
Test :: ~Test()
{
}
int main()
{
Test a(2);//带参构造函数
Test b(3);//带参构造函数
a = b;//赋值构造函数
Test c = a;//拷贝构造函数
b.func(a);实际上a是作为参数传递给b.func(Test temp),即Test temp = a;和上一个一致,是拷贝构造函数,不是赋值构造函数。
return 0;
}
拷贝构造函数的参数之所以使用引用类型是为了避免拷贝构造函数无限制的递归下去