#include <iostream> using namespace std; class Parent { public: Parent(){} Parent(int a):m_a(a){} Parent(const Parent& other):m_a(other.m_a) { cout<<"Parent 拷贝构造函数"<<endl; } Parent& operator= (const Parent& other) { cout<<"Parent 重载赋值运算符"<<endl; if(this == &other) return *this; m_a = other.m_a; return *this; } private: int m_a; }; class Child : public Parent { public: Child(){} Child(int a, int b):Parent(a), m_b(b){} Child(const Child& other) { m_b = other.m_b; cout<<"Child 拷贝构造函数"<<endl; } Child& operator= (const Child& other) { cout<<"Child 重载赋值运算符"<<endl; if(this == &other) return *this; m_b = other.m_b; return *this; } private: int m_b; }; int main() { Child child1(2, 3); Child child2(child1); Child child3 = child1; return 0; }
输出结果:
#include <iostream> using namespace std; class Parent { public: Parent(){} Parent(int a):m_a(a){} Parent(const Parent& other):m_a(other.m_a) { cout<<"Parent 拷贝构造函数"<<endl; } Parent& operator= (const Parent& other) { cout<<"Parent 重载赋值运算符"<<endl; if(this == &other) return *this; m_a = other.m_a; return *this; } private: int m_a; }; class Child : public Parent { public: Child(){} Child(int a, int b):Parent(a), m_b(b){} Child(const Child& other) : Parent(other) //调用父类的拷贝构造函数 { // Parent::Parent(other); //调用父类的拷贝构造函数(同上面的初始化列表) m_b = other.m_b; cout<<"Child 拷贝构造函数"<<endl; } Child& operator= (const Child& other) { cout<<"Child 重载赋值运算符"<<endl; Parent::operator=(other); //调用父类的重载赋值运算符 if(this == &other) return *this; m_b = other.m_b; return *this; } private: int m_b; }; int main() { Child child1(2, 3); Child child2(child1); Child child3 = child1; return 0; }
输出结果: