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/