您的位置:首页 > 编程语言 > C语言/C++

C++调用成员函数需要this指针的情况

2014-08-08 21:32 561 查看

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;
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: