c++ 构造函数、赋值构造函数、拷贝构造函数 例子备忘

xiaoxiao2025-08-15  24

class classA { public: int a; int *b; classA():a(2),b() { cout << "classA()" << endl; b = new int[2]; }; ~classA() { cout << "~classA()" << endl; delete[] b; }; classA(const classA& info) { cout << "classA(const classA& info)" << endl; a = info.a; b = new int[2]; b[0] = info.b[0]; b[1] = info.b[1]; } classA& operator = (const classA& info) { cout << "classA& operator = (const classA& info)" << endl; a = info.a; b[0] = info.b[0]; b[1] = info.b[1]; return *this; } }; class classB :public classA { public : int c; int *d; classB() :c(3) { cout << "classB()" << endl; d = new int[2]; }; ~classB() { cout << "~classB()" << endl; delete[] d; }; classB(const classB& info):classA(info) { cout << "classB(const classB& info):classA(info)" << endl; c = info.c; d = new int[2]; d[0] = info.d[0]; d[1] = info.d[1]; } classB& operator = (const classB& info) { if (this == &info) { return *this; } classA::operator=(info); cout << "classB& operator = (const classB& info) " << endl; c = info.c; d[0] = info.d[0]; d[1] = info.d[1]; return *this; } };

 

转载请注明原文地址: https://www.6miu.com/read-5034889.html

最新回复(0)