本节内容 对象拷贝 视频提供:昆山爱达人信息技术有限公司
1、什么是对象拷贝? O1 O2 O3 O1 O2 O3 O4 ...
2、拷贝构造函数: class CObject { private: int x; int y; public: CObject() } CObject(int x,int y) this->x = x; this->y = y; }; 拷贝构造函数的调用: CObject x(1,2); <1> CObject y(x); <2> CObject * p = new CObject(x);
3、父类也会拷贝吗? class Base { private: int m; public: Base(){} Base(int m) this->m = m; } }; class MyObject:public Base { private: int x; int y; public: MyObject() } MyObject(int x,int y,int k):Base(k) this->x = x; this->y = y; };
4、拷贝构造函数的问题: class MyObject { private: int m_nLength; char* m_strBuffer; public: MyObject() } MyObject(const char* str) m_nLength = strlen(str)+1; m_strBuffer = new char[m_nLength]; memset(m_strBuffer,0,m_nLength); strcpy(m_strBuffer,str); ~MyObject() delete[] m_strBuffer; }; 观察内存: MyObject m("china"); MyObject n(m);
5、自己添加拷贝构造函数: MyObject(const MyObject& obj) { m_nLength = obj.m_nLength; m_strBuffer = new char[m_nLength]; memset(m_strBuffer,0,m_nLength); strcpy(m_strBuffer,obj.m_strBuffer); } 注意:拷贝构造函数的格式是固定的
6、总结: 1、如果不需要深拷贝,不要自己添加拷贝构造函数。 2、如果你添加了拷贝构造函数,那么编译器将不在提供,所以的事情都需要由新添加的函数自己来处理: MyObject(const MyObject& obj):Base(obj) //1 { printf("拷贝构造函数执行了 \n"); this->x = obj.x; this->y = obj.y; //...哪些成员需要拷贝 不能有遗漏 //2 }
课后练习: <汇编、C/C++线上班>学员可见