看看这个多重继承的问题,也许对你有帮助

broaden 2002-07-19 09:27:27
源文件:

#include "stdafx.h"
#include "iostream.h"

class A
{
public:
virtual int ax()=0;
virtual int ay()=0;
};

class X:public A
{
public:
virtual int xx()=0;
virtual int xy()=0;
};

class B
{
public:
virtual int bx()=0;
virtual int by()=0;
};

class C:public X,public B
{
public:
virtual int ax(){cout<<"ax function"<<endl;return 0;}
virtual int ay(){cout<<"ay function"<<endl;return 0;}
virtual int xx(){cout<<"xx function"<<endl;return 0;}
virtual int xy(){cout<<"xy function"<<endl;return 0;}
virtual int bx(){cout<<"bx function"<<endl;return 0;}
virtual int by(){cout<<"by function"<<endl;return 0;}
};

int main(int argc, char* argv[])
{
void *pa=static_cast<B*>(new C);
((A*)pa)->ax();
((A*)pa)->ay();
return 0;
}

输出:
bx function
by function
...全文
42 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
ajoo 2002-07-21
  • 打赏
  • 举报
回复
it is the downcast that needs to be blamed, not the vtable scheme. My friend.
broaden 2002-07-21
  • 打赏
  • 举报
回复
vtable scheme
broaden 2002-07-20
  • 打赏
  • 举报
回复
sorry, it isn't a example with problem

这是多重继承和纯抽象基类的运用,并不是一个有问题的程序.
COM正是利用这个特性来支持聚合的.

我贴出来只是希望大家对此有所了解.
blade_fj 2002-07-20
  • 打赏
  • 举报
回复
right!
that is the point!
ajoo 2002-07-20
  • 打赏
  • 举报
回复
the lesson is:
don't always use downcast.
no matter static_cast or dynamic_cast.

One rule: down cast are all bad!
ajoo 2002-07-20
  • 打赏
  • 举报
回复

"COM正是利用这个特性来支持聚合的"
This is a wrong statement. using C++'s vtable scheme, COM has no way to escape from this problem, so it has to address this issue.
But that does not mean it 利用这个特性 to support aggregation.

And what 特性 do you mean? downcast or vtable scheme?
chenybin 2002-07-20
  • 打赏
  • 举报
回复
谢谢
UP
ForApply 2002-07-20
  • 打赏
  • 举报
回复
sorry!
public-->protected
ForApply 2002-07-20
  • 打赏
  • 举报
回复
聚合是COM中比较常见的方法
例如你需要一个车的对象,你可以从行驶控制+外观两种类中继承得到
但如果你需要在车的基础上再构造火车
那我建议你你不要再从车的对象派生了,
你需要改变一种策略
如下

class C车
{
public:
C行驶控制
C外观
}
class C火车
{
public:
C行驶控制
C外观
}

以避免车和火车不能复用同样的逻辑,
那个时候,由于对象之间的分别已经通过聚合被隐藏,代码是混杂在一起的,改动是非常麻烦而且容易出错的
ForApply 2002-07-20
  • 打赏
  • 举报
回复
说实话,原则上我觉得这种方法是有有点,但是弱点是非常明显的
虽然我的系统中大量使用了多继承,单都仅仅是在顶层
也就是中间层不做多继承
如下
interface A,B--->class C1
interface C----->class C2

不要再使用
class C1,C2----->Class C3

如果interface A,B,C中有一个MFC类,那么建议你不要使用上述方法,因为在指针转换过程中会存在问题
如果interface A,B,C中有两个以上MFC类,那么禁止使用上述方法,因为CObject的指针会有问题

16,473

社区成员

发帖
与我相关
我的任务
社区描述
VC/MFC相关问题讨论
社区管理员
  • 基础类社区
  • Web++
  • encoderlee
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

        VC/MFC社区版块或许是CSDN最“古老”的版块了,记忆之中,与CSDN的年龄几乎差不多。随着时间的推移,MFC技术渐渐的偏离了开发主流,若干年之后的今天,当我们面对着微软的这个经典之笔,内心充满着敬意,那些曾经的记忆,可以说代表着二十年前曾经的辉煌……
        向经典致敬,或许是老一代程序员内心里面难以释怀的感受。互联网大行其道的今天,我们期待着MFC技术能够恢复其曾经的辉煌,或许这个期待会永远成为一种“梦想”,或许一切皆有可能……
        我们希望这个版块可以很好的适配Web时代,期待更好的互联网技术能够使得MFC技术框架得以重现活力,……

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