code
#include <iostream>
using namespace std;
class C {
public:
int x;
C () {}
C(int a) : x(a) {}
// member function
C operator = (const C&);
};
C C::operator= (const C& param) {
x = param.x;
return *this;
}
int main()
{
C foo(1);
cout <<"foo.x = " << foo.x << endl;
C bar;
bar = foo;
cout <<"bar.x = " << bar.x << endl;
return 0;
}
run
foo.x = 1
bar.x = 1
ERROR
opeartor= must be a nonstatic member function
note
引用
Notice that some operators may be overloaded in two forms: either as a member function or as a non-member function
许多运算符可以作为 member function 以及 non-member function 两种形式被重载
说明
- 所谓member function就是code部分所示的那样,在类的定义中有一个关于需要被重载的运算符的简单声明,比如:
C operator = (const C&);
这里重载了运算符=(等号);
- 与之相对的,non-member function 就是类定义里没有这种语句的,比如某个类的完整定义只有下面这些组成:
class D {
public:
int y;
D () {}
D (int b) : y(b) {}
};
-
- C++中有许多运算符,比如=(等号),只能作为member function被重载,也就是说,必须在类的定义里声明一下,见code;
-
- 同时的,也有些运算符,比如+(加号),可以既作为 member function 又作为non-member function被重载。
疑惑
在我阅读的toturial[1]Classes (II)/The keyword this 部分的示例代码如下:
CVector& CVector::operator= (const CVector& param)
{
x=param.x;
y=param.y;
return *this;
}
注意,这里写得是CVector&
,参照这个代码写的类C
,那么对于=(等号),就应该写成C&
,但是这样编译器(DEV C++ ISO C++11)会报ERROR,修改成最终code部分才能通过编译,这是目前自己的代码和示例代码不一致的地方。
reference
Classes (II)
http://www.cplusplus.com/doc/tutorial/templates/