两个不同私有属性的重载 += 运算符
Overload += operator for two differents private attributes
是否可以为类中的两个不同的私有属性重载 += 运算符?
我正在尝试做这样的事情:
const int &Test::operator+=(const int &rhs)
{
*this = *this + rhs;
return *this;
}
这是我的班级:
class Test
{
private:
int _n;
int _n2;
public:
int getN();
void setN(int n);
int getN2();
void setN2(int n);
const int &operator+=(const int &rhs);
}
我假设您希望能够独立使用+=
进行_n
和_n2
。
请注意,我的示例并不完整。我省略了初始化和其他部分以减少腹胀。
1) 封装您的int
class Number
{
public:
Number& operator += (int rhs)
{
_n += rhs;
return *this;
}
int get() const;
void set(int n);
protected:
int _n;
};
class Test
{
public:
Number& n()
{ return _n; }
const Number& n() const
{ return _n; }
Number& n2()
{ return _n2; }
const Number& n2() const
{ return _n2; }
private:
Number _n;
Number _n2;
};
int main()
{
Test t;
t.n() += 24; // add to _n
t.n2() += 42; // add to _n2
return 0;
}
2) 使用两个单独的基类
class N
{
public:
N& operator += (int rhs)
{
_n += rhs;
return *this;
}
int getN() const;
void setN(int n);
protected:
int _n;
};
class N2
{
public:
N2& operator += (int rhs)
{
_n2 += rhs;
return *this;
}
int getN2() const;
void setN2(int n);
protected:
int _n2;
};
class Test
: public N
, public N2
{};
int main()
{
Test t;
// add to _n
t.N::operator += (24); // explicit operator
static_cast<N&>(t) += 24; // explicit cast
// add to _n2
t.N2::operator += (42); // explicit operator
static_cast<N2&>(t) += 24; // explicit cast
return 0;
}
相关文章:
- 继承函数的重载解析
- 如何导出包含具有"std::unique_ptr"值的"std::map"属性的
- 你能重载对象变量名本身返回的内容吗
- 从父命名空间重载类型
- 使用C++中的模板和运算符重载执行矩阵运算
- 为什么这个运算符<重载函数对 STL 算法不可见?
- 重载操作程序时出错>>用于类中的字符串 memebr
- 一个关于在C++中重载布尔运算符的问题
- 不同翻译单元中不可重载的非内联函数定义
- 为什么使用SFINAE而不是函数重载
- C++概念:如何使用'concept'检查模板化结构的属性?
- 为什么我不能在 C++ 中的特定函数重载中调用同一函数的任何其他重载?
- 将重载的成员函数传递给函数模板
- 子目录是否继承属性,例如add_definitions,include_directories和父Cmakelist.t
- 重载>>运算符未在输入上设置属性
- 两个不同私有属性的重载 += 运算符
- C++ 运算符重载:将 A 的类型 B 的属性值分配给 B 对象
- C++等于(==)重载,比较所有属性的快捷方式或最佳方法
- 如何重载其参数仅由gcc矢量扩展vector_size属性不同的函数
- 结构属性操作符重载