2010-10-07 80 views
1

可能重复:
Trouble with inheritance of operator= in C++运营商=在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=? 
+1

我刚刚回答了这个问题。可能的重复[在C++中运算符的继承问题](http://stackoverflow.com/questions/3882186/trouble-with-inheritance-of-operator-in-c) – AnT 2010-10-07 14:48:10

回答

4

隐式声明的拷贝赋值运算符看起来像

Derived& operator=(const Derived&); 

这隐含声明函数调用operator=每个基类和成员子对象(这就是为什么Baseoperator=过载被称为)。

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

+0

copy c'tor,c'tor和d'tor以同样的方式工作? – rookie 2010-10-07 14:50:10

+0

@rookie:是的,有效。 – 2010-10-07 14:51:27

2

这是因为

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

隐藏从基类的分配

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

。这与名称查找和范围有关。在隐藏检查您最喜爱的C++书籍。