81.类成员函数指针高级
1 #include <iostream> 2 using namespace std; 3 4 //myclass类 5 class myclass 6 { 7 public: 8 int add(int a, int b) 9 { 10 return a + b; 11 } 12 int sub(int a, int b) 13 { 14 return a - b; 15 } 16 int mul(int a, int b) 17 { 18 return a * b; 19 } 20 int divv(int a, int b) 21 { 22 return a / b; 23 } 24 }; 25 26 //类成员函数当做引用参数 27 void change(int(myclass::*&p)(int, int)) 28 { 29 p = &myclass::sub; 30 } 31 32 //changeit的参数是类成员函数指针的引用,返回值是类成员函数指针的引用 33 //类成员函数指针作为参数退化为二级类成员函数指针 34 int(myclass::*& changit( int(myclass::* &p)(int, int) ) )(int, int) 35 { 36 p = &myclass::sub; 37 return p; 38 } 39 40 void main() 41 { 42 myclass *pclass(nullptr);//空指针 43 //int(myclass::*p)(int, int) = &myclass::add;//类成员函数指针 44 //cout << pclass->add(1, 2) << endl; 45 //cout << (pclass->*p)(2, 3) << endl; 46 int(myclass::*p[4])(int, int) { &myclass::add, &myclass::sub, &myclass::mul, &myclass::divv }; 47 //下标方式循环 48 for (int i = 0; i < 4; i++) 49 { 50 //调用类成员函数数组 51 cout << (pclass->*p[i])(100, 10) << endl; 52 } 53 54 //指针方式循环(二级类成员函数指针遍历类成员函数指针) 55 for (int(myclass::**pp)(int, int) = p; pp < p + 4; pp++) 56 { 57 cout << (pclass->**pp)(100, 10) << endl; 58 } 59 60 //在堆上创建类成员函数指针 61 int (myclass::**p2)(int,int) = new (int(myclass::*[4])(int,int)){ &myclass::add, &myclass::sub, &myclass::mul, &myclass::divv }; 62 for (int i = 0; i < 4; i++) 63 { 64 //调用类成员函数数组 65 cout << (pclass->*p2[i])(100, 10) << endl; 66 } 67 68 int(myclass::*p3)(int, int) = &myclass::add; 69 change(p3); 70 (pclass->*p3)(12, 2); 71 cin.get(); 72 }