如何在C ++中定义其父级之外的嵌套类

时间:2015-07-17 18:19:39

标签: c++

我有两个类,A和B.除了A类并且需要私有访问A的成员之外,B类没有任何意义,所以我觉得它应该是一个私有的嵌套类。

A类已经很复杂了,所以我想把B类的定义保留在A类之外,也许是在一个单独的标题中。

我试过了......

class A;

class A::B
{
  int i;
};

class A
{
  class B;

  B my_b;
  int i;
};

int main (void)
{
  A my_a;
  return 0;
}

获取error: qualified name does not name a class before ‘{’ token

我试试这个......

class A
{
  class B;

  B my_b;
  int i;
};

class A::B
{
  int i;
};

int main (void)
{
  A my_a;
  return 0;
}

获取error: field ‘my_b’ has incomplete type ‘A::B’

这类似于How to write the actual code from a nested class outside the main class,但由于A类有A :: B作为成员这一事实而复杂化。

1 个答案:

答案 0 :(得分:6)

您可以指向B作为成员或智能指针。你不能拥有类型B的成员变量并在A之外定义它的原因是,如果编译器没有看到类的定义,它不知道它的大小因此无法弄清楚布局A

整个事情的另一种方法是使用pimpl习语,我认为这将是理想的。