C++类成员函数指针,二级类成员函数指针知识点

主要记录了类成员函数指针的语法,调用方式的学习

#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();
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值