1.什么时候会调用拷贝构造函数?
-
#include <iostream>
using namespace std;class CCTest{
public:
int m_nTest2;
CCTest(int x,int y): m_nTest(x) ,m_nTest2(y)
{
cout <<"constructor with argument"<<endl;
}
CCTest(const CCTest &ex)//
{
m_nTest = ex.m_nTest;
m_nTest2 = ex.m_nTest2;
cout<<"copy constructor"<<endl;
}
int GetVal()
{
return m_nTest;
}
CCTest& operator = (const CCTest &ex) //赋值运算符重载
{
this->m_nTest = ex.m_nTest;
this->m_nTest2 = ex.m_nTest2;
cout <<"assignment operator" <<endl;return *this;
}void myTestFunc(CCTest ex)//参数为引用的话调用该函数时,拷贝构造函数不会被调用
{
}CCTest testFunc2()// 如果返回的是对象的引用,则不会调用拷贝构造函数
{
cout<<"testFunc2() with a class obj returned!"<<endl;
CCTest a(1,1);
CCTest &b =a;
return b;
}
~CCTest()
{
}
private:
int m_nTest;
};int main()
{
CCTest aaa(2,1);
CCTest bbb(aaa); //1.用类的对象去初始化另一个对象
CCTest ccc = aaa;ccc.myTestFunc(aaa); //2.形参为类对象,实参初始化形参
CCTest ddd = ccc.testFunc2(); //3.函数返回一个类对象时
return 0;
}
运行结果:constructor with argument
copy constructor
copy constructor
copy constructor
testFunc2() with a class obj returned!
constructor with argument
copy constructorr
写了个以类指针为参数的“拷贝构造函数”
CCTest(CCTest *p)
{
m_nTest = p->m_nTest;
m_nTest2 = p->m_nTest2;
cout <<"copy constructor with point arg"<<endl;
}
在mian()函数中 CCTest aaa(2,1); CCTest *p = &aaa; CCTest bbb(p) ;//CCTest bbb = p也可以
运行结果:constructor with argument
copy constructor with point arg
至于拷贝构造函数的参数为什么规定为类对象的引用,结合众多网友的见解:1.历史原因 2.以指针作为参数只适用于某些简单的情况,如果一个函数的返回值为类指针,此时内存管理很不方便 3.引用使代码的可读性和维护性更好
ps:若有纰漏之处,请大神多多指教,不喜勿碰哟!