繁体   English   中英

C++ 中的子 class 重载加法运算符

[英]Overloading addition operator in child class in C++

好吧,伙计们想象一下我有一个父 class 和一个成功的重载 + 运算符的情况:

   class parent
   {
      public:
         int a; 
         int b;

         friend parent& operator+(parent& mother, const parent& father)
         {
            //add stuff
         }
   }
   class child : public parent
   {
      public:
         int q;

      friend child& operator+(child& brother, const child& sister)
         {
            output = brother.parent + sister.parent;
            output.q = brother.q + sister.q
         }
   }

如何正确重载该子加法运算符以调用父级,添加父级 class 的所有成员,然后添加子级 class 的成员? 在任何地方都找不到这方面的任何信息...

谢谢大家

我希望以下内容有所帮助。

class parent{
public:
    int a;
    int b;

    parent& operator+=(const parent& rhs){
        this->a += + rhs.a;
        return *this;
    }

    parent(int aa=0, int bb=0):a{aa},b{bb}{}

    friend parent& operator+(parent& mother, const parent& father){
        mother.a += father.a;
        mother.b += father.b;
        return mother;
    }
};
class child : public parent{
public:
    parent par;
    int q;

    child(int aa=0, int bb=0, int qq=0):par{aa,bb},q{qq}{}

    child& operator+=(const child& rhs){
        this->par += rhs.par;
        this->q += rhs.q;

        this->q += this->par.a;
        this->q += this->par.b;
        return *this;
    }

    friend child& operator+(child& brother, const child& sister)
    {
        brother.par += sister.par;
        brother.q += sister.q;
        // add parent.q and child.a child.b
        brother.q += brother.par.a;
        brother.q += brother.par.b;
        return brother;
    }
};

int main() {
    child c1{1,2,10}, c2{1,3,100}, c3{1,2,10}, c4{1,3,100};

    std::cout << c1.par.a << endl;
    std::cout << c1.par.b << endl;
    std::cout << c1.q << endl;

    c1 = c1+c2;
    std::cout << c1.q << endl;

    c3 += c4;
    std::cout << c3.q << endl;

    return 0;
}

除了您的代码中提到的其他问题外,您的实际问题的答案是:

  • 将基类调用编写为合格的 function 名称: parent::operator+(left,right);
  • 使用引用转换: (parent&)left + (const parent&)right;

暂无
暂无

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

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