主要记录了类成员函数指针的语法,调用方式的学习
#include <iostream>
#include <cstdlib>
using namespace std;
class Student{
public:
int c;
Student(int x):c(x){
}
int add(int a,int b){
//this->c = 1;
return a + b;
}
int sub(int a ,int b){
return a - b;
}
int divv(int a ,int b){
return a / b;
}
};
void maintest(){
//Student* stu = new Student(10);
//Student* stu(nullptr);
类成员函数指针
//int(Student::*p)(int, int) = &Student::add;
//
cout << stu->add(20, 30) << endl;
类成员函数指针,空指针可以调用没有成员变量的函数
cout << (stu->*p)(22, 33) << endl;
cout << ((*stu).*p)(11, 22) << endl;
//int(Student::*pp[3])(int, int) = { &Student::add, &Student::sub, &Student::divv };
//cout << sizeof(pp) << endl;
//for (int i = 0; i < 3; i++){
// cout << (stu->*pp[i])(12,3) << endl;
//}
//for (int(Student::**ppp)(int, int) = pp; ppp < pp + 3; ppp ++ ){
// cout << (stu->**ppp)(20,2) << endl;
//}
cin.get();
}
//改变类成员函数指针
void change( int(Student::*&p)(int,int) ){
p = &Student::divv;
}
//返回值是函数指针引用
int(Student::*& getFunc( int(Student::*&p)(int,int)))(int, int){
p = &Student::sub;
return p;
}
//类成员函数指针数组做参数会退化为指针
void showSize( int(Student::*p[4])(int,int) ){
cout << sizeof(p) << endl;
}
void main(){
Student* stu(nullptr);
//int(Student::*p)(int, int)[3] = {&};
//类成员函数指针数组分配在堆区
int(Student::**pp)(int, int);
pp = new (int(Student::*[3])(int, int)){ &Student::add, &Student::sub, &Student::divv };
for (int(Student::**mpp)(int, int) = pp; mpp < pp + 3; mpp++){
cout << (stu->**mpp)(30,3) << endl;
}
cout << "=====================================" << endl;
int(Student::*myp)(int, int) = &Student::add;
change(myp);
cout << (stu->*myp)(10,2) << endl;
myp = getFunc(myp);
cout << (stu->*myp)(10, 2) << endl;
showSize(pp);
cin.get();
}