小编典典

C++ 嵌套类/前向声明问题

all

是否可以前向声明嵌套类,然后将其用作外部类的具体(不是指向/引用)数据成员的类型?

IE

class Outer;

class Outer::MaybeThisWay   // Error: Outer is undefined
{
};

class Outer
{
 MaybeThisWay x;

 class MaybeThatOtherWay;

 MaybeThatOtherWay y;   // Error: MaybeThatOtherWay is undefined
};

阅读 98

收藏
2022-07-27

共1个答案

小编典典

你不能像这样前向声明一个嵌套类。

根据您要执行的操作,也许您可以使用命名空间而不是外层的类。您可以前向声明这样的类没有问题:

namespace Outer {
   struct Inner; 
};

Outer::Inner* sweets;  // Outer::Inner is incomplete so 
                       // I can only make a pointer to it

如果您的 Outer 绝对必须是一个类,并且您不能将它硬塞到命名空间中,那么您需要在转发声明 Inner 的上下文中将 Outer 设为完整类型。

class Outer
{
   class Inner;  // Inner forward-declared
};  // Outer is fully-defined now

Outer yes;  // Outer is complete, you can make instances of it
Outer::Inner* fun;  // Inner is incomplete, you can only make 
                    // pointers/references to it

class Outer::Inner 
{
};  // now Inner is fully-defined too

Outer::Inner win;  // Now I can make instances of Inner too
2022-07-27