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

查看:540
本文介绍了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

推荐答案

抽象类无法实例化,但是您要让编译器通过嵌入 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.

您可以通过稍微更改您的值来解决此问题设计并将 pointer (或智能指针,如果可以使用的话)嵌入到 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天全站免登陆