C++:不能将字段声明为抽象类型 [英] C++ : Cannot declare field to be of abstract type

查看:46
本文介绍了C++:不能将字段声明为抽象类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在编译时遇到此错误 -> 无法将字段 M1::sc 声明为抽象类型 I1,因为以下虚函数在 I1 中是纯的.请帮忙.

I get this error on compile -> cannot declare field M1::sc to be of abstract type I1 because the following virtual functions are pure within I1. Please help.

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

完整代码可以在 http://pastebin.com/PFrMTJuF 上找到.

Complete code can be found on http://pastebin.com/PFrMTJuF.

推荐答案

抽象类可以'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;
    }
}

这篇关于C++:不能将字段声明为抽象类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆