【C++ Primer | 14】重载运算

重载()运算符

 

 1 #include <iostream>
 2 using namespace std;
 3 
 4 class Distance
 5 {
 6 private:
 7   int feet;   // 0 到无穷
 8   int inches; // 0 到 12
 9 public:
10   // 所需的构造函数
11   Distance()
12   {
13     feet = 0;
14     inches = 0;
15   }
16   Distance(int f, int i)
17   {
18     feet = f;
19     inches = i;
20   }
21   // 重载函数调用运算符
22   Distance operator()(int a, int b, int c)
23   {
24     Distance D;
25     // 进行随机计算
26     D.feet = a + c + 10;
27     D.inches = b + c + 100;
28     return D;
29   }
30   // 显示距离的方法
31   void displayDistance()
32   {
33     cout << "F: " << feet << " I:" << inches << endl;
34   }
35 };
36 int main()
37 {
38   Distance D1(11, 10), D2;
39 
40   cout << "First Distance : ";
41   D1.displayDistance();
42 
43   D2 = D1(10, 10, 10); // invoke operator()
44   cout << "Second Distance :";
45   D2.displayDistance();
46 
47   return 0;
48 }

重载->运算符

 1 #include <iostream>
 2 using namespace std;
 3 
 4 class A
 5 {
 6 public:
 7     void display() { cout << "yes,ok" << endl; }
 8 };
 9 
10 class P
11 {
12 public:
13     P(A& ra) :ptr(&ra) {}
14     A* operator->() { return ptr; }
15 private:
16     A* ptr;
17 };
18 
19 class PP
20 {
21 public:
22     PP(A& ra) :p(ra) {}
23     P operator->() { return p; }
24 private:
25     P p;
26 };
27 
28 int main()
29 {
30     A a;
31     P p(a);
32     p->display();
33 
34     cout << endl;
35 
36     PP pp(a);
37     pp->display();
38     return 0;
39 }
View Code
原文地址:https://www.cnblogs.com/sunbines/p/13830273.html