use*_*767 20 c++ abstract-class
我在编译时遇到这个错误 - >不能将字段M1 :: sc声明为抽象类型I1,因为以下虚函数在I1中是纯的.请帮忙.
class I1
{
public:
virtual void a(int dir) = 0;
virtual void b() = 0;
virtual void c() = 0;
void a(int dir) {
....
}
void b() {
....
}
void c() {
....
}
};
class I2 : public I1
{
public:
void a(int dir) {
....
}
void b() {
....
}
void c() {
....
}
};
class M1 : public G1
{
protected:
I1 sc;
public:
int dir = 4;
sc.a(dir);
};
Run Code Online (Sandbox Code Playgroud)
完整的代码可以在http://pastebin.com/PFrMTJuF上找到.
Fré*_*idi 15
抽象类无法实例化,但是您要求编译器通过将实例嵌入I1到每个实例中来实现M1.
您可以通过稍微改变您的设计并将指针(或智能指针,如果您可以使用它们)嵌入到实例中I1来解决这个问题:
class M1 : public G1
{
protected:
I1 *sc;
public:
M1(I1 *sc_) {
sc = sc_;
}
void foo() {
int dir = 4;
sc->a(dir);
}
};
Run Code Online (Sandbox Code Playgroud)
编辑:在阅读完代码后,我认为解决问题的最简单,最简洁的方法是将当前房间传递给Execute()您的命令方法,例如:
class ICommand
{
public:
virtual ~ICommand()
{
}
virtual void Execute(Room *room) = 0;
};
class MoveCommand : public GameCommand
{
public:
MoveCommand()
{
}
void Execute(Room *room)
{
// Do something with `room`...
}
};
void Game::HandleInput()
{
// Read command from user and generate a command object from it.
ICommand *pCommand = ParseCommand(Input::ReadCommand());
if (pCommand) {
pCommand->Execute(GetCurrentRoom()); // Pass current room to command.
delete pCommand;
}
}
Run Code Online (Sandbox Code Playgroud)
I1 是一个抽象类,因为它具有纯虚函数(=没有定义的函数).
你不能创建抽象类的实例(因为它们如何工作?!),因此声明如I1 a无效.
在您对问题进行编辑之后,似乎I1不应该是一个抽象类,因为您提供了方法的定义.如果是这种情况,只需删除= 0方法声明之后的代码即可使代码工作.
| 归档时间: |
|
| 查看次数: |
41513 次 |
| 最近记录: |