c++模板下运算符重载标准写法

 1 #include <iostream>
 2 #include <cstring>
 3 #include <cassert>
 4 #include <conio.h>
 5 #include <memory>
 6 
 7 using namespace std;
 8 
 9 //注意:模板参数T总是未知的,并不保证能用<<, +, +=等运算符,这里只是做个示范
10 template <typename T>
11 class KaGa
12 {
13 private:
14     T data;
15 public:
16     KaGa(): data(T()) { }
17     KaGa(T data_): data(data_) { }
18     void add(const KaGa<T> &rhs) { this->data += rhs.data; }
19 
20     //重载+=运算符
21     template <typename U>
22     friend KaGa<U> &operator+=(KaGa<U> &lhs, const KaGa<U> &rhs);
23 
24     //重载<<运算符
25     template <typename U>
26     friend ostream &operator<<(ostream &out, const KaGa<U> &temp);
27 };
28 
29 //+重载函数定义
30 template <typename T>
31 KaGa<T> operator+(KaGa<T> lhs, const KaGa<T> &rhs) {
32     lhs.add(rhs);
33     return lhs;
34 }
35 
36 //+=重载函数定义
37 template <typename T>
38 KaGa<T> &operator+=(KaGa<T> &lhs, const KaGa<T> &rhs) {
39     lhs.data += rhs.data;
40     return lhs;
41 }
42 
43 //<<重载函数定义
44 template <typename T>
45 ostream &operator<<(ostream &out, const KaGa<T> &temp) {
46     out << temp.data;
47     return out;
48 }
49 
50 
51 int main(void)
52 {
53     int A = 1, B = 2, C = 3, D = 4;
54     KaGa<int> a(1), b(2), c(3), d(4);
55 
56     A += (B + C + D);
57     a += (b + c + d);
58     cout << "A = " << A << endl;
59     cout << "a = " << a << endl;
60 
61     A += B += C;
62     a += b += c;
63     cout << "A = " << A << ", B = " << B << ", C = " << C << endl;
64     cout << "a = " << a << ", b = " << b << ", c = " << c << endl;
65 
66     getch();
67     return 0;
68 }

运行结果:

猜你喜欢

转载自www.cnblogs.com/AIKaGa/p/12766310.html