我有 2 个类,基类(带有复制构造函数)和派生类,在基类 I 中重载了 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 {
};
当我尝试做那样的事情时
Derived x;
Derived y;
Derived c=x+y;
我得到错误: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);
}
这很完美,因为当遇到 e+f
时,编译器找到基类的 operator+
,他隐式地从 Derived
转换为Base
,并计算一个 Base
类型的结果。您可以轻松编写 c=e+f
。
缺少什么?
问题仅从分配给派生对象开始。一旦你尝试 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"; }
};
一旦你定义了它,一切都会如你所愿:
g=e+f; // will automatically construct a Derived from the result
// and then execute `Derived`'s default `operator=` which
// will call `Base`'s `operator=`
这里是live demo .
关于c++ - 运算符+在基类中重载并在派生类中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30138023/