C++學習——day6 成員函數指針、多態、虛函數

函數指針

#include<iostream>
using namespace std;


void show(int a)
{
	cout << "show inta" << endl;
}

class A
{
public:
	static void show1(int a)
	{
		cout << "111" << endl;
	}
protected:
private:
};

int main()
{
	void(*pfun)(int);//定義函數指針
	pfun = &show;//賦值
	(*pfun)(1);//調用

	typedef void(*PFUN)(int);//自定義函數指針類型
	PFUN p;
	p = &show;
	(*p)(1);

	PFUN p1;
	p1 = &A::show1;//必須指向類中的靜態函數


	return 0;
}

成員函數指針

#include<iostream>
using namespace std;

class A
{
public:
	void show(int a)
	{

	}
protected:
private:
};
int main()
{
	void (A::*fun)(int);
	fun = &A::show;//定義
	A a;
	(a.*fun)(1);//調用
	A* pa;
	(pa->*fun)(1);
	return 0;
}

虛函數

#include<iostream>
using namespace std;
class Student
{
public:
	virtual void study() = 0;
};
class Student1:public Student
{
public:
	void study()
	{

	}
};
class Student2 :public Student
{
public:
	void study()
	{

	}
};
void studentstudy(Student* stu)
{
	stu->study();//體現多態
}
int main()
{
	Student1 stu1;
	Student2 stu2;
	studentstudy(&stu1);
	studentstudy(&stu2);


	return 0;
}

虛函數實現多態的原理

【vptr指針】:指向類的虛函數指針列表。調用不同子類時,vptr發生變化指向子類的虛函數列表從而調用子類的函數。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章