简体   繁体   中英

Overloading addition operator in child class in C++

Okay guys imagine situation where I have a parent class and a successfuly overloaded + operator:

   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
         }
   }

How can I correctly overload that child addition operator to call the parent, add all the members off the parent class, then add the members of the child class? Can't find any info on this anywhere...

Thanks all

I hope the following helps.

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;
}

Besides the other problems noted with your code, the answer to your actual question is to either:

  • write the base-class call as a qualified function name: parent::operator+(left,right);
  • use a reference cast: (parent&)left + (const parent&)right;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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