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

时间:2013-01-23 08:00:32

标签: 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

1 个答案:

答案 0 :(得分:1)

是的,您可以在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