7,540
社区成员
发帖
与我相关
我的任务
分享
// TestClass.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
class Interface
{
public:
Interface(){}
~Interface(){}
//
virtual void PrintFloat(const float &A_Float) = 0;
};
class Base
{
public:
Base(){}
virtual ~Base(){}
//
void PrintBase(){printf("Base\n");}
virtual void PrintInt(const int &A_Int) = 0;
virtual void PrintAB(const int &A_A,const int &A_B) = 0;
};
class Child : public Base
{
public:
Child(){}
~Child(){}
//
void PrintInt(const int &A_Int){printf("Child PrintInt %d\n",A_Int);}
};
class Grandson : public Child,public Interface
{
public:
Grandson(){}
~Grandson(){}
//
void PrintAB(const int &A_A,const int &A_B){printf("Grandson PrintAB %d %d\n",A_A,A_B);}
void PrintFloat(const float &A_Float){printf("Grandson PrintFloat %f\n",A_Float);}
};
int _tmain(int argc, _TCHAR* argv[])
{
Base * l_pBase = new Grandson();
Interface *l_p = (Interface*)l_pBase;
l_p->PrintFloat(123.1);
delete l_p;
//
printf("===============================");
char l_chr;
scanf_s("%c",&l_chr);
return 0;
}
l_p->PrintFloat(123.1);
delete l_p;
是我疏忽了。但我认为它不是重点。
关于下面这句
Interface *l_p = (Interface*)(Grandson*)l_pBase;
为什么这样改就对?而且如果【Interface *l_p】是形参的话,从结构上说不知道有个【Grandson】类型。
int main(int argc, char* argv[])
{
//申请一块内存,并且在这块内存中放置一个Grandson的实体
//但是该指针类型只能访问Base类型的接口
Base * l_pBase = new Grandson();
//指针仍然指向Grandson的实体,但是该指针父类型只能访问Interface类型的接口
//虚函数处在一个指针表里面,正确的方法是使用dynamic_cast<>操作符
//古老的C语言的强制转换不适用在含有虚表的类型中
//Interface *l_p = (Interface*)l_pBase;
//l_p->PrintFloat(123.1);
Interface *l_p = dynamic_cast<Interface*>(l_pBase);
if(l_p)
{
l_p->PrintFloat(123.1);
}
//总结:你这是不好的编程习惯
//向下类型转化,应该使用dynamic_cast<>操作符,并且判断是否转换成功
//此处应该使用l_pBase,避免未完全释放
//delete l_p;
delete l_pBase;
printf("===============================\n");
return 0;
}