我有这样的代码:
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 类中
void operator = (const Base& base_)
{
Base::operator=(base_);
}
然后一切都编译好了。虽然我不认为这会很好,因为如果我有 5 个从 Base 继承的不同类,那么我必须在每个派生类中重复相同的代码。
NOTE:我的复制意图Base
to Child
就是简单地复制成员common二者皆是Base
and Child
(这将是所有成员Base
)。即使在阅读了下面的所有答案之后,我真的不明白为什么 C++ 不允许这样做,特别是如果有一个明确的operator=
定义在Base
class.
该标准在 12.8/10“复制类对象”(添加了重点)中提供了您的具体问题的原因:
因为如果用户未声明,则为类隐式声明复制赋值运算符,基类复制赋值运算符始终被派生类的复制赋值运算符隐藏(13.5.3)。
所以既然有一个隐式声明operator=(const Child&)
当编译器执行名称查找/重载解析时Child::operator=()
, the Base
类的函数签名甚至从未被考虑过(它是隐藏的)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)