C++ 为什么我不能将基类分配给子类?

标签 c++ inheritance

我有这样的代码:

class Base
{
public:
  void operator = (const Base& base_)
  {
  }
};

class Child : public Base
{
public:

};

void func()
{
  const Base base;
  Child child;
  child = base;
}

我的问题是:既然 Child 派生自 Base(因此它应该继承 Base 的 operator= ),为什么当语句出现时

child = base;

被执行,我得到这样的编译器错误:

>.\main.cpp(78) : error C2679: binary '=' : no operator found which takes a right-hand operand of type 'const Base' (or there is no acceptable conversion)
1>        .\main.cpp(69): could be 'Child &Child::operator =(const Child &)'
1>        while trying to match the argument list '(Child, const Base)'

我想要的行为是让 Child 类识别它被分配了一个 Base 类,并且只是“自动”调用其父类的 operator=。

一旦我将此代码添加到 Child 类中

void operator = (const Base& base_)
{
  Base::operator=(base_);
}

然后一切都编译好了。虽然我不认为这会很好,因为如果我有 5 个继承自 Base 的不同类,那么我必须在每个派生类中重复相同的代码。

注意:我将 Base 复制到 Child 的目的是简单地复制 common 的成员BaseChild(这将是 Base 的所有成员)。即使在阅读了下面的所有答案之后,我真的不明白为什么 C++ 不允许这样做,尤其是当 Base 中定义了一个显式的 operator= 时> 类。

最佳答案

该标准在 12.8/10“复制类对象”(添加了重点)中提供了您的具体问题的原因:

Because a copy assignment operator is implicitly declared for a class if not declared by the user, a base class copy assignment operator is always hidden by the copy assignment operator of a derived class (13.5.3).

因此,当编译器为 Child::operator=() 执行名称查找/重载解析时,由于存在隐式声明的 operator=(const Child&)Base 类的函数签名从未被考虑过(它是隐藏的)。

关于C++ 为什么我不能将基类分配给子类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2241835/

相关文章:

c++ - 通过结构化绑定(bind)从对/元组元素移动

c++ - make 没有执行正确的 Makefile

c++ - 多重继承 - virtual 修饰符

C++ 在扩展模板类时定义特定的对象类型

java - 在java中将抽象类作为参数传递

c++ - XSD : How to make a polymorphic "list"?

c++ - 头文件中的多重定义

c++ - 子对象和包含对象之间的区别

继承引用成员的构造函数中的 C++ 默认初始化

java - ArrayList 和 Arrays.asList 在继承情况下对 Collection 的工作方式不同