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