首页 > 解决方案 > 初始化在同一头文件中定义的底层的顶层类

问题描述

可能是个愚蠢的问题。我很抱歉,但我想做以下事情,

connectionState currentState;

class connectionState {
    public:
        .......
        .......
};

相当

class connectionState {
    public:
        .......
        .......
};

connectionState currentState;

前者根本不编译,而后者则编译。那么,没有办法做到这一点吗?

标签: c++classc++11namespaces

解决方案


对此有前向声明。前向声明也解决了循环依赖的问题:

class connectionState; // forward class declaration
extern connectionState currentState; // forward global extern variable declaration, now possible because connectionState is declared as a typename/class name
static connectionState currentState; // forward global static variable declaration 

class connectionState { ... }; // implementation/definition, can access currentState
connectionState currentState = ...; // definition/initialization
connectionState currentState {...}; // definition/initialization

推荐阅读