非成员 += C++重载
non member += overloading in C++
#include <iostream>
class A
{
public:
int a;
A() { a = 2;}
A(int f) { a= f;}
void print() { std::cout << a << std::endl; }
};
class B
{
A a, at, at2;
A& operator += (A& b)
{
a.a = a.a + b.a;
return a;
}
public:
B(int a_, int at_, int at2_) : a(a_), at(at_), at2(at2_) {};
void update ()
{
a += at;
}
void printAll() { a.print(); at.print();}
};
int main()
{
B value ( 2, 3, 5);
value.printAll();
value.update();
value.printAll();
}
错误是:
temp.cpp:24:10:错误:与"((B*)this)->B::a += ((B*)this)->B::at"中的"运算符+="不匹配
我做错了什么?
您定义的运算符是 A & operator+=(B &, A & )
,而不是 A & operator+=(A &, A &)
。所以你已经定义了如何向B
添加A
,但没有定义如何将A
添加到A
。在class A
的定义之后但在class B
的定义之前尝试这样做:
A & operator+=(A & a1, const A & a2) { a1.a += a2.a; return a1; }
但这种运算符更自然地定义为成员函数。
A& B::operator += (A& b)
方法
A & operator+=(B &, A & )
您只需要将operator +=(const A&b)
添加到 A 类
class A
{
//....
A& operator += (const A& b)
{
a += b.a;
return *this;
}
//....
};
非成员版本为:
A & operator+=(A a1, const A & a2) { a1.a += a2.a; return a1; }
相关文章:
- 继承函数的重载解析
- 你能重载对象变量名本身返回的内容吗
- 从父命名空间重载类型
- 使用C++中的模板和运算符重载执行矩阵运算
- 为什么这个运算符<重载函数对 STL 算法不可见?
- 重载操作程序时出错>>用于类中的字符串 memebr
- 一个关于在C++中重载布尔运算符的问题
- 不同翻译单元中不可重载的非内联函数定义
- 为什么使用SFINAE而不是函数重载
- 为什么我不能在 C++ 中的特定函数重载中调用同一函数的任何其他重载?
- 将重载的成员函数传递给函数模板
- c++:可变模板和函数重载
- 重载元组索引运算符-C++
- 如何使用重载的相等(==)运算符向测试用例添加描述
- 重载==不适用于二进制树
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 重载运算符new[]的行为取决于析构函数
- 正在尝试重载二进制搜索树分配运算符
- 重载Singly Linked List中的赋值运算符
- 取消引用运算符不能重载