我有一个非常简单的基类/派生类场景:
#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;
}
Run Code Online (Sandbox Code Playgroud)
我上面说明的初始实现将无法编译.有谁能解释为什么?我觉得因为gdbChannel明确是BaseChannel的一个实例,所以不需要强制转换.
And*_*owl 10
那是因为gdbChannel不使用public继承来派生BaseChannel(class类型的默认值是private).
如果公共继承是你想表达的,那就写下:
class gdbChannel : public BaseChannel{
// ^^^^^^
public:
void SayBoo(bool SelectAll) {if (SelectAll) cout<<"boo";}
};
Run Code Online (Sandbox Code Playgroud)