0
我有一个非常简单的基类/派生类的场景:C++不能转换派生类基础
#include <tchar.h>
#include <stdio.h>
#include <iostream.h>
#include <conio.h>
class BaseChannel{
private:
public:
virtual ~BaseChannel(){};
virtual void SayBoo(bool SelectAll)=0;
};
class gdbChannel: BaseChannel{
public:
void SayBoo(bool SelectAll) {if (SelectAll) cout<<"boo";}
};
class UsesChannel{
public:
BaseChannel * c;
};
int _tmain(int argc, _TCHAR* argv[])
{
gdbChannel gc;
UsesChannel uc;
// uc.c = &gc; //cannot convert gdbChannel* to BaseChannel*
uc.c = (BaseChannel*)&gc; // works
uc.c->SayBoo(true);
getch();
return 0;
}
我的初步实施,上文评论说,将无法编译。谁能解释为什么?我觉得由于gdbChannel是显式的BaseChannel的实例,所以不需要强制转换。
哇,那是快!这个例子显然是派生出来的,但我认为我已经在主要例子中尝试过了。谢谢@Andy – marcp 2013-04-30 18:12:38
@marcp:不客气,很高兴帮助:) – 2013-04-30 18:12:53