简体   繁体   English

重载运算符+

[英]Overloading operator+

I'm looking for an elegant solution to the following "problem": 我正在寻找以下“问题”的优雅解决方案:

Consider the classes Base and Child, and the way operator+ works here: 考虑类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 ****

}

The marked lines in main give the error: cannot convert from 'const Base' to 'Child' main中标记的行给出错误: 无法从'const Base'转换为'Child'

I understand perfectly that the operator has been defined in the Base class, and returns an object of type Base , which can't be converted to Child . 我完全理解运算符已在Base类中定义,并返回Base类型的对象,该对象无法转换为Child One solution is overloading operator+ for the Child class, but I am wondering whether there is a better, less costly method. 一个解决方案是为Child类重载operator + ,但我想知道是否有更好,更低成本的方法。 I'm under the impression that I'm forgetting a much easier option. 我的印象是我忘记了一个更容易的选择。 Thanks! 谢谢!

you can define a constructor Child(Base& obj) then Child c=(a+b); 你可以定义一个构造函数Child(Base& obj)然后Child c=(a+b); statement will be fine and then you can use the base object as per your requirement. 语句可以正常,然后您可以根据您的要求使用基础对象。

There is no easier option. 没有更容易的选择。

Operator overloading and class hierarchies don't really like to mix. 运算符重载和类层次结构实际上并不喜欢混合。 I'm personally very suspicious when a type that should be a value type (or else why are you overloading operators?) is part of a hierarchy. 当一个应该是值类型的类型(或者你为什么要重载运算符?)时,我个人非常怀疑是层次结构的一部分。 Can you describe your actual architecture? 你能描述一下你的实际架构吗? Does it actually make sense to overload the operator there? 在那里重载操作员真的有意义吗?

If you want to build a child from a base without adding the appropriate constructor, there is another alternative. 如果你想在没有添加适当构造函数的情况下从基础构建子代,还有另一种选择。 You can declare the casting operator in your base class, returning your mValue : 您可以在基类中声明转换运算符,返回mValue

operator int() const;

This way, the compiler will do the job implicitly. 这样,编译器就会隐式地完成这项工作。

PS : Ensure const-correctness of your additive operator : PS :确保添加剂操作符的正确性:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM