C++ 源文件中的嵌套类定义

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4482005/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 15:30:38  来源:igfitidea点击:

Nested Class Definition in source file

c++inner-classesmember

提问by Samaursa

If I have a nested class like so:

如果我有一个像这样的嵌套类:

  class MyClass
  {
    class NestedClass
    {
    public:
      // nested class members AND definitions here
    };

    // main class members here
  };

Currently, the definitions of MyClassare in the CPPfile but the definitions for NestedClassare in the header file, that is, I cannot declare the functions/constructors in the CPPfile.

目前, 的定义MyClassCPP文件中,而 的定义NestedClass在头文件中,也就是说,我不能在CPP文件中声明函数/构造函数。

So my question is, how do I define the functions of NestedClassin the cpp file? If I cannot, what is the reason (and if this is the case, I have a vague idea of why this happens but I would like a good explanation)? What about structures?

所以我的问题是,如何定义NestedClasscpp 文件中的函数?如果我不能,原因是什么(如果是这种情况,我对为什么会发生这种情况有一个模糊的想法,但我想要一个很好的解释)?结构呢?

回答by sje397

You can. If your inner class has a method like:

你可以。如果你的内部类有一个类似的方法:

  class MyClass   {
    class NestedClass
    {
    public:
      void someMethod();
    };

    // main class members here
  };

...then you can define it in the .cpp file like so:

...然后您可以在 .cpp 文件中定义它,如下所示:

void MyClass::NestedClass::someMethod() {
   // blah
}

Structures are almost the same thing as classes in C++ — just defaulting to 'public' for their access. They are treated in all other respects just like classes.

结构与 C++ 中的类几乎相同——只是默认为“公共”以供访问。他们在所有其他方面都像类一样被对待。

You can(as noted in comments) just declare an inner class, e.g.:

可以(如评论中所述)只声明一个内部类,例如:

class MyClass   {
    class NestedClass;
    // blah
};

..and then define it in the implementation file:

..然后在实现文件中定义它:

class MyClass::NestedClass {
  // etc.
};