C++面向对象2

本文探讨了C++中子类构造函数未显式调用父类拷贝构造函数导致的bug,解释了为何基类部分默认使用缺省构造函数初始化可能带来的问题,并给出了正确的拷贝构造函数实现。通过实例演示了如何确保在拷贝创建Derived对象时正确复制Base部分。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  • 以下程序的输出为:

class Base
{
public:
    Base(int val = 0):m_x(val){cout<<__FUNCTION__<<1<<endl;}
    Base(const Base& oth):m_x(oth.m_x){cout<<__FUNCTION__<<2<<endl;}
    int m_x = -1;
};
class Derived:public Base
{
public:
    Derived(int val):Base(val), m_y(val){cout<<__FUNCTION__<<3<<endl;}
    Derived(const Derived& oth):m_y(oth.m_y){cout<<__FUNCTION__<<4<<endl;}
    int m_y;
};

int main()
{
    Derived d1(10);
    Derived d2 = d1;
    cout<<d2.m_x << " " << d2.m_y << endl;

    return 0;
}

输出为:
Base::Base1
Derived::Derived3
Base::Base1
Derived::Derived4
0 10

子类的构造函数因为没有显示的在初始化序列化表里调用父类的拷贝构造函数,编译器默认就调用父类的没有参数的构造函数,即调用父类的Base(int val = 0);

类derived展现了一个在所有c++环境下都会产生的bug:当derived的拷贝创建时,没有拷贝其基类部分。当然,这个derived对象的base部分还是创建了,但它是用base的缺省构造函数创建的,成员x被初始化为0(缺省构造函数的缺省参数值),而没有顾及被拷贝的对象的x值是多少!

为避免这个问题,derived的拷贝构造函数必须保证调用的是base的拷贝构造函数而不是base的缺省构造函数。这很容易做,只要在derived的拷贝构造函数的成员初始化列表里对base指定一个初始化值:
 

class Base
{
public:
    Base(int val = 0):m_x(val){cout<<__FUNCTION__<<1<<endl;}
    Base(const Base& oth):m_x(oth.m_x){cout<<__FUNCTION__<<2<<endl;}
    int m_x = -1;
};
class Derived:public Base
{
public:
    Derived(int val):Base(val), m_y(val){cout<<__FUNCTION__<<3<<endl;}
    //Derived(const Derived& oth):Base(oth), m_y(oth.m_y){cout<<__FUNCTION__<<4<<endl;}
    Derived(const Derived& oth):Base(oth.m_x), m_y(oth.m_y){cout<<__FUNCTION__<<4<<endl;}
    int m_y;
};


int main()
{
    Derived d1(10);
    Derived d2 = d1;
    cout<<d2.m_x << " " << d2.m_y << endl;

    return 0;
}

输出为:

Base::Base1
Derived::Derived3
Base::Base2或Base::Base1
Derived::Derived4
10 10

现在,当用一个已有的同类型的对象来拷贝创建一个derived对象时,它的base部分也将被拷贝了。

https://www.cnblogs.com/vigorz/p/10499230.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值