java中变量与对象存储_将派生类对象存储在基类变量中

TL;DR: You should not inherit from a publicly copyable/movable class.

实际上,在编译时可以防止对象切片:在此上下文中,基础对象不应该是可复制的 .

案例1:抽象基础

如果基础是抽象的,那么它就无法实例化,因此您无法体验切片 .

案例2:具体基础

如果基础不是抽象的,则可以复制它(默认情况下) . 你有两个选择:

完全阻止复制

仅允许儿童复制

注意:在C 11中,移动操作会导致相同的问题 .

// C++ 03, prevent copy

class Base {

public:

private:

Base(Base const&);

void operator=(Base const&);

};

// C++ 03, allow copy only for children

class Base {

public:

protected:

Base(Base const& other) { ... }

Base& operator=(Base const& other) { ...; return *this; }

};

// C++ 11, prevent copy & move

class Base {

public:

Base(Base&&) = delete;

Base(Base const&) = delete;

Base& operator=(Base) = delete;

};

// C++ 11, allow copy & move only for children

class Base {

public:

protected:

Base(Base&&) = default;

Base(Base const&) = default;

Base& operator=(Base) = default;

};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值