且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C++:不能将字段声明为抽象类型

更新时间:2022-11-24 07:37:24

抽象类可以't 被实例化,但您要求编译器通过将 I1 的实例嵌入到 M1 的每个实例中来做到这一点.

Abstract classes can't be instantiated, but you're asking the compiler to do just that by embedding an instance of I1 into every instance of M1.

您可以通过稍微更改您的设计并将指针(或智能指针,如果可以使用的话)嵌入到 I1 的实例来解决这个问题:

You can work around that by slightly changing your design and embedding a pointer (or a smart pointer, if you can use those) to an instance of I1 instead:

class M1 : public G1
{
protected:
    I1 *sc;
public:
    M1(I1 *sc_) {
        sc = sc_;
    }
    void foo() {
        int dir = 4;
        sc->a(dir);
    }
};

阅读您的代码后,我认为解决您的问题的最简单,最干净的方法是将当前房间传递给您的 Execute() 方法命令,例如类似:

After reading your code, I think that the simplest and cleanest way to solve your problem is to pass the current room to the Execute() method of your command, e.g. something like:

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;
    }
}