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;
}
输出结果:
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;
}
输出结果: