c++ - 如何在派生类中实现“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.a和b1.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
..的字段?
解决方案
给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 链接)。
推荐阅读
- python - shutil.copy() 在起点和终点之间出现错误:FileNotFoundError: [WinError 3] 系统找不到指定的路径
- java - 什么更有效率?将拆分字符串存储在数组中,或在每次需要时调用拆分方法
- laravel - laravel 前端排队作业的实时进度
- python - 如何获取最大操作的索引
- css - webkit背景过滤器在放大后工作
- php - 用php设置输入最大长度
- javascript - 在 Jquery 中获取自动完成的选定值
- mongodb - 返回实际文档而不是 ObjectId
- excel - MDX:过滤器函数中的集合表达式是什么?
- sql - 使用 DECLARE 和将值传递给存储过程之间有区别吗