一 概述 前面所讲的指针都是指向类外声明的函数,也就是说指向的都不是类的成员函数,本节我们将学习指向类的成员函数的指针,及成员函数指针。
二 示例演示及结果一 2.1 代码 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 #include<iostream> using namespace std; class A { private: int a; int b; public: void Set(int x,int y){a=x;b=y;} void show(){cout<<"a:"<<a<<"\t"<<"b:"<<b<<endl;} }; void(A::*p)(int,int); int main() { A a; p=&A::Set; int x=2,y=3; (a.*p)(x,y); a.show(); return 0; }
2.2 输出结果
三 示例演示及结果二 3.1 代码 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 #include<iostream> using namespace std; class Human { public: virtual void run()=0; virtual void eat()=0; }; class Mother: public Human { public: virtual void run() { cout << "母亲跑百米要花二十秒" << endl; } virtual void eat() { cout << "母亲喜欢吃零食" << endl; } }; class Father: public Human { public: virtual void run() { cout << "父亲跑百米要花十秒" << endl; } virtual void eat() { cout << "父亲不喜欢吃零食" << endl; } }; class Uncle: public Human { public: virtual void run() { cout << "舅舅跑百米要花十五秒" << endl; } virtual void eat() { cout << "舅舅喜欢偷吃零食" << endl; } }; int main() { void (Human::*pf)(); Human *p = 0; char choice1, choice2; bool quit = false; while (quit == false) { cout << "(0)退出(1)母亲(2)父亲(3)舅舅:"; cin >> choice1; switch (choice1) { case '0': quit = true; break; case '1': p = new Mother; break; case '2': p = new Father; break; case '3': p = new Uncle; break; default: choice1 = 'q'; break; } if (quit) { break; } if(choice1=='q') { cout<<"请输入0到3之间的数字"<<endl; continue; } cout<<"(1)跑步(2)进食"<<endl; cin>>choice2; switch(choice2) { case '1':pf=&Human::run; break; case '2':pf=&Human::eat; break; default: break; } (p->*pf)(); delete p; } return 0; }
3.2 输出结果 1 2 3 4 5 6 7 8 9 10 11 12 13 (0)退出(1)母亲(2)父亲(3)舅舅:1 (1)跑步(2)进食 1 母亲跑百米要花二十秒 (0)退出(1)母亲(2)父亲(3)舅舅:2 (1)跑步(2)进食 1 父亲跑百米要花十秒 (0)退出(1)母亲(2)父亲(3)舅舅:3 (1)跑步(2)进食 1 舅舅跑百米要花十五秒 (0)退出(1)母亲(2)父亲(3)舅舅: