类体内的前向声明是否被视为其他类型?

Gam*_*anA 3 c++ inner-classes forward-declaration c++11

我在一个封闭的类中有两个内部结构,在其中一个结构中,我有一个指向另一个结构类型的对象的指针成员。为了提高可读性并明确指出前向声明适用于需要它的结构,我将前向声明放在内部结构本身中。像这样

class Enclosing{
public:
    struct InnerA{
       struct InnerB; // forward declaration inside InnerA to improve readability  
       InnerB* b; 
       // other members
   };

    struct InnerB{

       // lots of member variables
    };
};
Run Code Online (Sandbox Code Playgroud)

然后在外面的某个地方我有一个功能

void DoSomething(){
    Enclosing::InnerA a;


    // error incompatible types Enclosing::InnerB* and Enclosing::InnerA::InnerB*
    Enclosing::InnerB* ptr = a.b; 
}
Run Code Online (Sandbox Code Playgroud)

据我了解,前向声明仅是一种告诉编译器类的方法,而不是定义完全不同的新类型。这是标准吗?如果是这样,是否有一种方法可以在结构内部包含前向声明而不将其视为其他类型?

alt*_*gel 7

是的,它被认为是另一种类型。

声明将名称放入声明出现的范围。每个类都介绍自己的范围。因此,就您而言,您有Enclosing::InnerA::InnerB,这显然不同于Enclosing::InnerB

恐怕除了当前名称外,无法在其他范围内声明名称。您只需在定义使用位置之前InnerB直接在中声明。EnclosingInnerA