C ++ Complete Reference说:“除了=运算符,运算符函数由派生类继承。”
但我无法理解以下代码的行为:
#include<iostream>
using namespace std;
int main(){
class b{
int i;
public:
int operator=(b parm){
cout<<"base overload";
};
};
class d: public b{
int j;
public:
};
b inst1,inst11;
d inst2,inst22;
int a;
inst1=inst11; //works because assignment operator is overloaded for b
inst2=inst22; //If =operator function is not inherited then why does it output "base oberload"
inst1=inst2; //works because assignment overloaded for b
// inst2=inst11; //But if b was inherited then this should also work but it doesnt
}
我期待两个输出语句“基本过载”,但它输出三个为什么?这让我疯狂
答案 0 :(得分:0)
operator=
未被继承。但编译器将generate implicitly operator=
用于类d
,它会调用b::operator=
来分配基础子对象。
运算符使用标量的内置赋值和类类型的复制赋值运算符,按初始化顺序执行对象基础和非静态成员的成员方式复制分配。
然后
inst2=inst22; //If =operator function is not inherited then why does it output "base oberload"
此处调用生成的d::operator=
;在其中调用b::operator=
。
这里调用inst1=inst2; //works because assignment overloaded for b
b::operator=
,它期望b
作为参数,inst2
可以隐式转换为基类b
。
尝试在此处调用// inst2=inst11; //But if b was inherited then this should also work but it doesnt
d::operator=
,它期望d
作为参数,但inst11
无法隐式转换为派生类d
。< / p>