bin*_*157 2 c++ inheritance operator-overloading
我有2个类,base(带有复制构造函数)和派生,在baseΙ有重载operator+
:
class Base {
public:
Base(const Base& x) {
// some code for copying
}
Base operator+(const Base &bignum) const {
Base x;
/* ... */
return x;
}
};
class Derived : public Base {
};
Run Code Online (Sandbox Code Playgroud)
当我尝试做那样的事情
Derived x;
Derived y;
Derived c=x+y;
Run Code Online (Sandbox Code Playgroud)
我得到错误:conversion from "Base" to non-scalar type "Derived" derived
问题可能在于该运算符+返回Base
类型的对象,我想将它分配给Derived
类型对象?
事实上,你不需要重新定义operator+
(除非你的设计需要它,正如Ajay的例子所指出的那样).
采取以下简约示例:
struct Base {
Base operator+ (Base a) const
{ cout <<"Base+Base\n"; }
Base& operator= (Base a)
{ cout<<"Base=Base\n"; }
};
struct Derived : public Base { };
int main() {
Base a,b,c;
c=a+b; // prints out "Base+Base" and "Base=Base"
Derived e,f,g;
e+f; // prints out "Base+Base" (implicit conversion);
}
Run Code Online (Sandbox Code Playgroud)
这非常有效,因为当遇到e+f
编译器找到operator+
基类时,他会隐式转换Derived
为Base
,并计算类型的结果Base
.你可以轻松写c=e+f
.
问题始于仅对Derived的分配.一旦你尝试,g=e+f;
你会收到一个错误.编译器不确定如何将A放入B中.这种谨慎是通过普遍的智慧证明的:所有类人猿都是动物,但所有动物都不一定是猿.
如果Derived
有更多的字段,那就更明显了Base
:应该如何编译它们?基本上,如何告诉编译器他将如何制作Derived
出其他东西?用构造函数!
struct Derived : public Base {
Derived()=default;
Derived(const Base& a) : Base(a) { cout<<"construct B from A\n"; }
};
Run Code Online (Sandbox Code Playgroud)
一旦你定义了这个,一切都按照你的期望工作:
g=e+f; // will automatically construct a Derived from the result
// and then execute `Derived`'s default `operator=` which
// will call `Base`'s `operator=`
Run Code Online (Sandbox Code Playgroud)
这是一个现场演示.
归档时间: |
|
查看次数: |
5848 次 |
最近记录: |