可以通过以下的方式实现:
- 定义全局函数
- 在类中使用友元函数
- 使用类成员函数进行重载
定义的形式:
Test operator + (const Test& obj);
实例:
1 #include <iostream>
2
3 using namespace std;
4
5 class Complex
6 {
7 int _real;
8 int _imaginary;
9 public:
10 Complex(int real, int imaginary)
11 {
12 this->_real = real;
13 this->_imaginary = imaginary;
14 }
15 int getReal()
16 {
17 return _real;
18 }
19 int getImaginary()
20 {
21 return _imaginary;
22 }
23
24 Complex operator + (const Complex& obj)
25 {
26 int r = this->_real + obj._real;
27 int i = this->_imaginary + obj._imaginary;
28
29 return Complex(r, i);
30 }
31 };
32
33 int main(int argc, char** argv)
34 {
35 Complex c1(1, 2);
36 Complex c2(3, 4);
37
38 Complex c3 = c1 + c2;
39
40 cout << c3.getReal() << endl;
41 cout << c3.getImaginary() << endl;
42
43 return 0;
44 }
在Pangolin 的example 中看到这样一段:
struct CustomType
{
CustomType()
: x(0), y(0.0f) {}
CustomType(int x, float y, std::string z)
: x(x), y(y), z(z) {}
int x;
float y;
std::string z;
};
std::ostream& operator<< (std::ostream& os, const CustomType& o){
os << o.x << " " << o.y << " " << o.z;
return os;
}
std::istream& operator>> (std::istream& is, CustomType& o){
is >> o.x;
is >> o.y;
is >> o.z;
return is;
}
这里也是重载了操作符<< 和 >>