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

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

2015-07-08 15:53 851 查看

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

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