类成员函数

 1 /* 类成员函数 */
 2 
 3 
 4 #include<iostream>
 5 
 6 using namespace std;
 7 
 8 // 类成员函数指针  类成员二级函数指针  类成员函数指针数组
 9 
10 
11 class op
12 {
13 public:
14     op(int x,int y):a(x),b(y)
15     {
16         
17     }
18 
19     int add(int a,int b)
20     {
21         return a+b;
22     }
23     
24 
25     int mul(int a,int b)
26     {
27         return a*b;
28     }
29 
30     int divv(int a,int b)
31     {
32         return a/b;
33     }
34 
35     int sub(int a,int b)
36     {
37         return a-b;
38     }
39 
40 private:
41     int a;
42     int b;
43 };
44 
45 
46 
47 
48 void main()
49 {
50     op op1(100,10);
51     
52     auto fun1 = &op::add;// 获取函数指针 fun1 无法调用
53 
54     cout << typeid(fun1).name() << endl;
55 
56     int(op::*p)(int a,int b) = &op::add;//创建类成员函数指针  指定对象来调用
57     
58     cout << (op1.*p)(40,50) << endl;// 调用方式,类成员函数传递this指针,也就是对象地址
59 
60     cin.get();
61 }
62 
63 
64 void main()
65 {
66     op op1(100,10);
67 
68     // 类的成员函数指针
69     int(op::*p[4])(int a,int b)={&op::add,&op::sub,&op::mul,&op::divv};// 类成员函数指针数组
70     
71     for (int i=0;i<4;i++)
72     {
73         cout << (op1.*p[i])(500,50) << endl;// 调用方式,类成员函数传递this指针,也就是对象地址
74     }
75     
76 
77     // int(op::**pp)(int a,int b); 类的二级成员函数指针
78     
79     for (int(op::**pp)(int a,int b) = p;pp<p+4;pp++ )
80     {
81         cout << (op1.**pp)(500,50) << endl;
82     }
83 
84 
85 
86 
87     cin.get();
88 }

 

posted on 2015-06-12 17:46  Dragon-wuxl  阅读(171)  评论(0)    收藏  举报

导航