c++ - 将基类对象分配给派生类对象

标签 c++ inheritance

    class Base{};
    class Derived: public Base{};

    int main()
    {
        Base B;
        Derived D;

        Base B1 = D;//OK
        Derived D1 = B;//error: conversion from ‘Base’ to non-scalar 
                       //type ‘Derived’ requested
        return 1;
    }

我知道派生类与基类具有 is-a 关系。

如何阻止派生 D1 具有来自 B 的值以及具有某些垃圾值的剩余成员变量(如果有)?

或者

错误信息是什么

conversion from ‘Base’ to non-scalar type ‘Derived’ requested Derived D1 = B;

说?什么是标量类型?

最佳答案

声明

Derived D1 = B;

是初始化,而不是赋值(即使它看起来像赋值)。

它尝试使用 Derived复制构造函数,但该复制构造函数需要一个参数 Derived const& 。还有B实例无法自动转换为完整Derived .

如果您确实想要切片分配 - 仅分配给 Base切片D1 – 那么您可以显式使用Base::operator= :

Derived D1;
D1.Base::operator=( B );

另一种表达方式:

Derived D1;
static_cast<Base&>( D1 ) = B;

但是味道很臭。 ;-)


回复

What is a scalar type?

这与“规模”中的词相同。标量类型提供单个大小值,以便该类型的值可以与 == 进行比较(理想情况下也是 < )。然而,在 C++ 中,指针甚至成员指针都被视为标量类型:

C++11 §3.9/9 [基本类型]:

Arithmetic types (3.9.1), enumeration types, pointer types, pointer to member types (3.9.2), std::nullptr_t, and cv-qualified versions of these types (3.9.3) are collectively called scalar types.

关于c++ - 将基类对象分配给派生类对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27949748/

相关文章:

c++ - Qt 渲染图像并显示它

c++ - 将值插入到标准 C++ 数组的正确索引(升序)中

c++ - 使用宏“覆盖”cmake 命令并恢复其默认行为

C++11 - 构造函数继承

python - 强制唯一与模型继承一起

java - Java中对象类的继承

c++ - C++远程读取文件

c++ - 属性 "deprecated"到 C++17 中的命名空间

javascript - javascript 超出最大调用堆栈大小

python - 从父类B使用父类A的方法