运算符重载举例
1 #include <iostream>
2 #include <string>
3
4 using namespace std;
5
6 class T
7 {
8 public:
9 int getAge();
10 string getName();
11 setName(string name);
12 setAge(int age);
13 friend T& operator+(T& tL, T& tR);
14 T& operator=(T& tR)
15 {
16 name = tR.getName();
17 age = tR.getAge();
18 return *this;
19 }
20 T(){};
21 ~T(){};
22 protected:
23 private:
24 string name;
25 int age;
26 };
27
28 int main(int argc, char* argv[])
29 {
30 T t1,t2;
31 t1.setAge(10);
32 t2.setAge(20);
33 t1.setName("QQ");
34 t2.setName("YY");
35 cout<<t1.getName()<<" is "<<t1.getAge()<<" years old!"<<endl;
36 cout<<t2.getName()<<" is "<<t2.getAge()<<" years old!"<<endl;
37 t2 = t1 = t1+t2;
38 cout<<t1.getName()<<" is "<<t1.getAge()<<" years old!"<<endl;
39 cout<<t2.getName()<<" is "<<t2.getAge()<<" years old!"<<endl;
40 return 0;
41 }
42
43 T& operator+(T& tL, T& tR)
44 {
45 tL.setAge(tL.getAge()+tR.getAge());
46 tL.setName(tL.getName()+tR.getName());
47 return tL;
48 }
49
50 int T::getAge()
51 {
52 return age;
53 }
54
55 string T::getName()
56 {
57 return name;
58 }
59
60 T::setAge(int age)
61 {
62 this->age=age;
63 }
64
65 T::setName(string name)
66 {
67 this->name=name;
68 }
运算符重载举例
时间: 2024-11-17 04:10:14