c++ - 重载运算符+

标签 c++ inheritance

我正在寻找以下“问题”的优雅解决方案:

考虑类 Base 和 Child,以及此处 operator+ 的工作方式:

class Base
{
public:
    Base(int a=0) : mValue(a) {};
    Base(const Base& rhs) : mValue(rhs.mValue) {};
    Base& operator=(const Base& rhs) {
        if (this==&rhs) return *this;
        mValue=rhs.mValue;
    }


    friend const Base operator+(Base &lhs, Base &rhs);

private:
    int mValue;
};

const Base operator+(Base &lhs, Base &rhs)
{
    Base result(lhs.mValue+rhs.mValue);
    return result;
}

class Child : public Base
{
public:
    Child(int a=0) : Base(a) {};
};

int main()
{
    Child a(2);
    Child b(5);
    Child c(a+b);  // **** This line ****
            Child d;
            d=(a+b); // **** or this other one ****

}

main 中标记的行给出了错误: 无法从“const Base”转换为“Child”

我完全理解,运算符已经定义在Base类中,返回的是Base类型的对象,无法转换为Child 。 一种解决方案是为 Child 类重载 operator+,但我想知道是否有更好、成本更低的方法。我的印象是我忘记了一个更简单的选择。谢谢!

最佳答案

你可以定义一个构造函数 Child(Base& obj) 然后 Child c=(a+b); 语句就可以了然后你可以使用基础对象作为根据您的要求。

关于c++ - 重载运算符+,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22507001/

相关文章:

c# - 继承基类时如何避免错误 "Constructor on type ' MyType'not found”

c++ - std::thread::join 在 libcxx 中实现在哪里

c++ - 在构建早期用于 ARM 的项目源时,基于 Windows,面临编译器错误 ""没有这样的指令 : 'ldr r13,[r1]'

c++ - 我想知道下面的指针等同是做什么的?

c++ - 内存中的继承保护成员变量拷贝

ruby 列出不是 mixins 的祖先

c++ - sibling 的 dynamic_cast 的用例是什么?

c++ - Xcode需要哪些设置才能构建此代码

c# - 实时视频流快速编码

Python 类继承函数并从 Child 传递参数