可能是个很基础的多继承问题,但是我不懂。望讲解。
例程如下,vs2012控制台程序
// 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);
这条语句的输出,何解???
------解决方案--------------------
应该输出这个:
Grandson PrintFloat 123.1
纯虚函数:调用指针实际所指向内存中类型的函数。
普通函数:指针什么类型,就调用什么类型里面的函数。
------解决方案--------------------
将l_pBase转为?Interface类型,因为Grandson继承自?Interface
------解决方案--------------------
int _tmain(int argc, _TCHAR* argv[])
{
Base * l_pBase = new Grandson();
Interface *l_p = (Interface *) (Grandson *)l_pBase; // mod here
l_p->PrintFloat(123.1);
delete l_pBase; // mod here
//
printf("===============================");
char l_chr;
scanf_s("%c",&l_chr);
return 0;
}