子类和父类的拷贝和赋值函数实现

本文深入探讨了C++中拷贝构造函数和赋值操作符的实现细节,通过具体示例,包括基类和派生类的拷贝构造与赋值过程,解析了对象初始化和赋值时的内存管理机制。

#include
using namespace std;
class Parent
{
public:
Parent(int a): m_a(a)
{}
Parent(const Parent &p)
{
cout << “parent copy function” << endl;
m_a = p.m_a;
}
Parent()
{}
Parent& operator=(const Parent &p)
{
cout << “parent = function” << endl;
if (this != &p)
{
this->m_a = p.m_a;
}
return *this;
}
void seta(int a)
{
this->m_a = a;
}
int geta()
{
return this->m_a;
}
private:
int m_a;
};
class Child:public Parent
{
public:
Child(int a, int b) :Parent(a), m_b(b) {}
Child(const Child &ch) :Parent(ch)
{
cout << “child copy function” << endl;
//Parent::Parent(ch);//这个打印出现乱码
this->m_b = ch.m_b;
}
Child()
{}
Child& operator=(const Child &ch)
{
cout << “child = function” << endl;
Parent::operator=(ch);
if (this != &ch)
{
this->m_b = ch.m_b;
}
return *this;
}
void setb(int b)
{
this->m_b = b;
}
int getb()
{
return this->m_b;
}
private:
int m_b;
};
int main()
{
Child ch1(10, 50);
cout << ch1.geta() << " " << ch1.getb() << endl;
Child ch2 = ch1;
cout << ch2.geta() << " " << ch2.getb() << endl;
Child ch3;
ch3 = ch1;
cout << ch3.geta() << " " << ch3.getb() << endl;
system(“pause”);
return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值