超载分配运算符的继承
Inheritance of Overloaded assignment Operator
c 完整参考说:"除了=操作员,操作员函数由派生类继承。"
,但我了解以下代码的行为:
#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
}
我期望两个输出语句"基本过载",但它正在输出三个为什么?这让我发疯
operator=
未继承。但是编译器将对d
类隐含生成operator=
,该类别调用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
。
相关文章:
- 通过继承类使用来自不同命名空间的运算符
- 运算符继承和 cpp 核心准则 c.128 的问题
- 如果我真的真的想从 STL 容器继承,并且我继承构造函数并删除新运算符,会发生什么?
- 继承模板化转换运算符
- C++ 继承运算符=
- 在继承的模板类中使用下标 [] 运算符
- 如何调用继承的重载运算符<<并在派生类的输出中添加更多文本?
- C++模板化类上继承的运算符'<<'
- 类继承和运算符重载
- 通过继承重载运算符会导致歧义
- 使用继承的指针列表复制构造函数或重载运算符=
- C++中移动赋值运算符的继承
- 如何在C++上的多个继承上下文上使用特定基类中的运算符
- 继承类中的比较运算符
- 继承 C++14 中的模板化运算符 =:g++ 和 clang++ 的不同行为
- 具有继承的未声明标识符(运算符 ostream)
- 如何使用运算符编写可继承的模板类
- C++继承运算符<<
- 继承运算符 +()
- 继承运算符*的问题