【问题标题】:Overloading addition operator in child class in C++在 C++ 中的子类中重载加法运算符
【发布时间】:2021-06-07 05:59:15
【问题描述】:

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

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

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

谢谢大家

【问题讨论】:

  • 对于初学者。 binary-add 应该按 value 返回。我会先修复这个计划中被破坏的小部分。
  • 如“父运算符+(父与母,常量父与父)”?我的意思是没问题,我可以解决这个问题,无论如何我已经在我的真实代码中实现了父类实现,但就是不知道如何处理子类
  • 我需要跑步,所以我无法写出正确的答案,但是here's an idea
  • 请注意,您可以通过使用 Ted 示例中的按值第一参数操作来放弃临时副本。例如。 like this。顺便说一句,值得一提的是,这种嵌套形式的对象初始化需要 C++17 或更高版本。你的解决方案不会,但测试程序肯定会。
  • 是的,我知道。正如我所展示的,不要复制。它是由调用者制作的。它还支持移动语义并使您的操作员具有异常安全性,这是我以这种方式引用它的主要原因。各有各的。

标签: c++ class oop c++11


【解决方案1】:

希望以下内容有所帮助。

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

【讨论】:

    【解决方案2】:

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

    • 将基类调用写为限定函数名:parent::operator+(left,right);
    • 使用参考转换:(parent&amp;)left + (const parent&amp;)right;

    【讨论】:

      猜你喜欢
      • 2021-07-10
      • 2021-05-14
      • 2020-10-18
      • 2021-07-09
      • 1970-01-01
      • 2011-12-04
      • 2013-10-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多