C ++我如何不能将一个基类分配给一个子类? [英] C++ How come I can't assign a base class to a child class?

查看:172
本文介绍了C ++我如何不能将一个基类分配给一个子类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的代码:

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的运算符=),语句如何出现

My question is: since Child derives from Base (hence it should inherit Base's operator= ), how come when the statement

child = base;

,我得到一个编译错误,如下所示:

is executed, I get a compiler error like this:

>.\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类,并只是自动调用其父的运算符=。

The behavior that I want is for the Child class to recognize that it's being assigned a Base class, and just "automatically" call the its parent's operator=.

一旦我添加这个代码到Child类

Once I added this code to the Child class

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

虽然我不认为这将是好的,因为如果我有5个不同的类继承Base,那么我必须重复相同的代码在每个单一的派生类。

then everything compiled fine. Though I dont think this would be good because if I have like 5 different classes that inherit from Base, then I have to repeat the same code in every single derived class.

注意:我打算将<​​code>基本复制到儿童基本公共 c $ c> Base )。即使在阅读所有下面的答案后,我真的不明白为什么C ++不允许这样做,特别是如果有一个明确的 operator = 定义在 Base class。

NOTE: My intention for copying the Base to Child is to simply copying the members that are common to both Base and Child (which would be all the members of Base). Even after reading all of the answers below, I really don't see why C++ doesn't allow one to do this, especially if there's an explicit operator= defined in the Base class.

推荐答案

标准提供了您的具体问题的原因12.8 / 10复制类对象(添加了强调):

The standard provides the reason for your specific question in 12.8/10 "Copying class objects" (emphasis added):


因为如果未声明(13.5.3)。

因此,当编译器执行<$ c $的名称查找/重载解析时,会隐式声明 operator =(const Child&) c> Child :: operator =(), Base 类的函数签名从未被考虑过(隐藏)。

So since there's an implicitly declared operator=(const Child&) when the compiler is performing the name lookup/overload resolution for a Child::operator=(), the Base class's function signature is never even considered (it's hidden).

这篇关于C ++我如何不能将一个基类分配给一个子类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆