关于多继承和纯虚函数问题

yinshi2006 2014-07-22 05:35:05
可能是个很基础的多继承问题,但是我不懂。望讲解。
例程如下,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);

这条语句的输出,何解???
...全文
400 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
yinshi2006 2014-07-23
  • 打赏
  • 举报
回复
感谢楼上指出。

delete l_p;
是我疏忽了。但我认为它不是重点。 关于下面这句

Interface *l_p = (Interface*)(Grandson*)l_pBase;
为什么这样改就对?而且如果【Interface *l_p】是形参的话,从结构上说不知道有个【Grandson】类型。
BillStone 2014-07-23
  • 打赏
  • 举报
回复
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; }
yinshi2006 2014-07-23
  • 打赏
  • 举报
回复
别的地方的回帖

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;
}
yinshi2006 2014-07-22
  • 打赏
  • 举报
回复
好吧,我没有说清楚。 我认为此程序理应得到,如下结果: Grandson PrintFloat 123.1 =============================== 但是实际结果是: =============================== 根本看不到 Grandson PrintFloat 123.1 觉得这个结果很莫名其妙,不知哪里错了。希望解释一下。 可以拿代码试一下,全在上面了。
bdmh 2014-07-22
  • 打赏
  • 举报
回复
将l_pBase转为 Interface类型,因为Grandson继承自 Interface
oldmtn 2014-07-22
  • 打赏
  • 举报
回复
应该输出这个: Grandson PrintFloat 123.1 纯虚函数:调用指针实际所指向内存中类型的函数。 普通函数:指针什么类型,就调用什么类型里面的函数。

7,540

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 VC.NET
社区管理员
  • VC.NET社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧