C ++中的运算符= [重复]

Posted

技术标签:

【中文标题】C ++中的运算符= [重复]【英文标题】:operator= in c++ [duplicate] 【发布时间】:2010-10-07 14:44:20 【问题描述】:

可能重复:Trouble with inheritance of operator= in C++

大家好,假设我有两个类:

Base; //inside I have operator=
Derived; //inside I don't have operator=

为什么这个工作完美:

Derived der1, der2;
der1=der2;  //<-here I know that it actually calls my Base::operator=

而这个不是:

Derived der1;
Base bas1;
der1=bas1;  //<-here why can't call Base::operator=?

【问题讨论】:

我刚刚回答了这个问题。 Trouble with inheritance of operator= in C++ 的可能重复项 【参考方案1】:

隐式声明的复制赋值运算符看起来像

Derived& operator=(const Derived&);

这个隐式声明的函数为每个基类和成员子对象调用operator=(这就是调用Baseoperator= 重载的原因。

bas1 的类型是Base,而不是Derived,并且没有从BaseDerived 的隐式转换,因此它不起作用。您需要声明一个适当的赋值运算符,以支持将 Base 类型的对象分配给 Derived 类型的对象(不过这有点不寻常)。

【讨论】:

copy c'tor、c'tor 和 d'tor 的工作方式一样吗?【参考方案2】:

那是因为

Derived& Derived::operator=(Derived const&);

隐藏分配

Base& Base::operator=(Base const&);

来自基类。这与名称查找和范围有关。查看您最喜欢的关于隐藏的 C++ 书籍。

【讨论】:

以上是关于C ++中的运算符= [重复]的主要内容,如果未能解决你的问题,请参考以下文章

c中的逗号运算符[重复]

C编程-while循环中的逗号运算符[重复]

在 C 中使用 ?: 运算符的复合 if 语句 [重复]

Java中的字符不会随后增量更新[重复]

C ++中的仿函数以防止重复?

kotlin中的三元运算符[重复]