1

我在 WinImp.h 中收到一个错误,上面写着'Root' has not been declared. 如果我不使用范围运算符 ( class WinImp : public BaseDef),则错误是error: expected class-name before '{' token)。有谁知道为什么会这样?

根目录

class Root {
    public:
        class BaseDef {
            public:
                virtual void foo() = 0;
                virtual void bar() = 0;
        };
    private:
        #ifdef _WIN32
        friend class WinImp;
        #else
        friend class NixImp;
        #endif

        BaseDef* imp;

        BaseDef* getImp();

    public:
        Root() : imp(getImp()) {}
        void foo();
        void bar();
};

根.cpp

#include "Root.h"
void Root::foo() {
    imp->foo();
}

void Root::bar() {
    imp->bar();
}

WinImp.h

#ifdef _WIN32
#include "Root.h"
class WinImp : public Root::BaseDef {
    public:
        void foo();
        void bar();
};
#endif

WinImp.cpp

#include "WinImp.h"
#ifdef _WIN32
    void WinImp::foo() {

    }

    void WinImp::bar() {

    }

    Root::BaseDef* Root::getImp() {
        return static_cast<BaseDef*>(new WinImp());
    }
#endif
4

2 回答 2

2

您正在访问BaseDefRoot 中的接口,因此它们应该是公开的:

class BaseDef 
{
 public:
   virtual void foo() = 0;
   virtual void bar() = 0;
};

在 WinImp.cpp 中,foo(), bar()需要返回类型并且它们不在 Root 范围内,应该是:

void WinImp::foo() { }
void WinImp::bar() { }
于 2013-01-25T22:15:09.823 回答
2

修复WinImp.cpp如下:

#include "WinImp.h"
#ifdef _WIN32
    // WinImp is not scoped within Root
    void WinImp::foo() {

    }

    void WinImp::bar() {

    }

    Root::BaseDef* Root::getImp() {
        return dynamic_cast<BaseDef*>(new WinImp());
    }
#endif
于 2013-01-25T22:20:43.287 回答