5

可能重复:
C++ 中嵌套类型/类的前向声明

对于类的简单交叉引用,预先声明类名并将其用作引用是可行的。以这种方式,表示是一个指针。但是如果我想交叉引用两者的嵌套类(看下面的例子),我会遇到麻烦,因为似乎没有办法预先声明一个嵌套类。

所以我的问题是:有没有办法预先声明嵌套类,以便我的示例可以工作?

如果没有:是否有一个通用的解决方法,这不会使代码过于丑陋?

// Need to predeclare it to use it inside 'First'
class Second;
class Second::Nested; // Wrong

// Definition for my 'First' class
class First
{
public:
    Second::Nested* sested; // I need to use the nested class of the 'Second' class.
                            // Therefore I need to predeclare the nested class.
    class Nested { };
};

// Definition for my 'Second' class
class Second
{
public:
    First::Nested* fested; // I need to use the nested class of the 'First' class.
                           // This is okay.
    class Nested { };
};
4

1 回答 1

4

简而言之,答案是否定的。

但是您应该首先寻找类似的问题...

编辑:一种可能的解决方法可能是将两个类包装在另一个类中,并在包装​​器内转发嵌套类。

class Wrapper
{
public:

   // Forward declarations
   class FirstNested;
   class SecondNested;

   // First class
   class First
   {
   public:
      SecondNested* sested;
   };

   // Second class
   class Second
   {
   public:
      FirstNested* fested;
   };
};

这样,您必须实现它们Wrapper::AWrapper::B同时仍将它们与您正在实施的任何命名空间隔离开来。

于 2012-05-13T11:21:06.210 回答