C++在一个文件中定义类,并在另一个文件中转发声明它

C++ Define Class in One File and Forward Declare It in Another

本文关键字:文件 另一个 转发 声明 定义 一个 C++      更新时间:2023-10-16

C++这样做是否合法/建议

//Interface.h
#ifndef INTERFACE_H
#define INTERFACE_H
    #include "WinImplementation.h"
    #include "NixImplementation.h"
    class Interface {
        class WinImplementation;
        class NixImplementation;
    }
#endif
//WinImplementation.h
#ifndef WINIMPLEMENTATION_H
#define WINIMPLEMENTATION_H
    #include "Interface.h"
    class Interface::WinImplementation {}
#endif
//NixImplementation.h
#ifndef NIXIMPLEMENTATION_H
#define NIXIMPLEMENTATION_H
    #include "Interface.h"
    class Interface::NixImplementation {}
#endif

是的,您可以在C++中转发声明嵌套类。 以下示例直接取自C++标准(第 9.7.3 节):

class E
{
    class I1;     // forward declaration of nested class
    class I2;
    class I1 {};  // definition of nested class
};
class E::I2 {};   // definition of nested class
相关文章: