首页 > 解决方案 > 如何在派生类中实现“operator+=”?

问题描述

给定以下类:

class A { 
int a;
public:
//..
};

class B : public A {
int b;
public:  
//.....
};

我怎样才能在给定的情况下实现operator+=class B如果B b1(.. , ..);B b2(.. , .. );这样做b1+=b2;,我将为b1他的字段输入以下值:

b1.a = b1.a + b2.ab1.b = b1.b + b2.b

在以下情况下:

class A { 
protected:
int a;
public:
//..
};

class B : public A {
int b;
public:  
B& operator+=(const B& bb){
this->a += bb.a; // error..
this->b += bb.b;
return *this;
};

我的问题是如何获得class A..的字段?

标签: c++c++11operator-overloading

解决方案


A自己operator+=!然后您只需从以下位置调用它B

class A { 
private:
    int a;
public:
    A(int a) : a(a) { } 

    A& operator+=(const A &other) {
        a += other.a;
        return *this;
    }   
};

class B : public A { 
private:
    int b;
public:
    B(int a, int b) : A(a), b(b) { } 

    B& operator+=(const B &other) {
        A::operator+=(other);
        b += other.b;
        return *this;
    }   
};

在此处查看一个工作示例(ideone 链接)。


推荐阅读