簡體   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