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

标签 c++ oop class forward-declaration

在 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

关于C++ 在一个文件中定义类并在另一个文件中转发声明它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14474905/

相关文章:

swift - 在 Swift 中枚举类成员

c++ - WMI 返回不同格式的信息

c++ - 在文本文件中识别编程语言的代码

c++ - 移动数组元素的功能不起作用

C++ STL容器插入拷贝

php - 使用 for 循环访问类变量

C++ 创建类对象和循环包含的问题

c++ - 按类型实例化 C++ lambda

java - 在JAVA中实例化一个抽象类?

javascript - 为什么类不适用于 Angular 指令?