c++ - 运算符+在基类中重载并在派生类中使用

标签 c++ inheritance operator-overloading

我有 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/

相关文章:

c++ - 以下问题的蛮力技术

c# - 具有实现多个接口(interface)的返回类型的方法

c++ - 如何在 C++ 中为数组重载运算符<<?

haskell - 在 Haskell 中定义一个新的 monad?

c++ - 在 C++ 中重载 += 运算符 - 如何传递左操作数?

c++ - 通过例程初始化聚合

c++ - 素数序列的回溯算法

c++ - 如何从 std::map 值的 std::vector 中找到最小键值?

css - textarea 不继承父元素的 css 颜色

java - 我应该对 bean 使用继承吗?