Nested Class Definition in source file

感情迁移 提交于 2019-11-29 02:14:24

问题


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 MyClass are in the CPP file but the definitions for NestedClass are in the header file, that is, I cannot declare the functions/constructors in the CPP file.

So my question is, how do I define the functions of NestedClass in 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?


回答1:


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:

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.

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.
};


来源:https://stackoverflow.com/questions/4482005/nested-class-definition-in-source-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!