C++调用一个成员函数的需求this指针的情况

1、虚成员函数,因为需要this展望虚表指针的指针


2、在数据成员的操作部件的功能

#include "stdafx.h"
#include <iostream>
#include <typeinfo>
using namespace std;

class A
{
public:
	virtual void foo()
	{
		cout<<"A foo"<<endl;
	}
	void pp()
	{
		cout<<"A PP"<<endl;
	}
};

class B:public A
{
public:
	B()
	{
		num=100;
	}
	void foo()
	{
		cout<<"B foo"<<endl;
	}
	void pp()
	{
		cout<<"B PP"<<endl;
	}
	void FunctionB()
	{
		cout<<"Excute FunctionB!"<<endl;
	}
	void show()
	{
		cout<<num;
	}
private:
	int num;
};

int main(int argc,char* argv[])
{
	A a;
	A* pa=&a;
	B *pb0,*pb;

	pb0->FunctionB();
	pb=dynamic_cast<B*>(pa);
	if(pb==NULL)
	{
		cout<<"The pointer pb is null"<<endl;
	}

	(dynamic_cast<B*>(pa))->FunctionB();
	(dynamic_cast<B*>(pa))->foo();						//运行出错,由于须要this指针
	(dynamic_cast<B*>(pa))->show();					//运行出错。由于须要this指针

	system("pause");
	return 0;
}


版权声明:本文博客原创文章,博客,未经同意,不得转载。

原文地址:https://www.cnblogs.com/zfyouxi/p/4630452.html