我在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();
};

根目录
#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

最佳答案

您正在Root中访问BaseDef接口(interface),因此它们假定是公共(public)的:

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

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

10-04 14:27