How to make an inner class without putting the definition of inner class to parent class?

ⅰ亾dé卋堺 提交于 2019-12-21 05:08:11

问题


I'll write an header file,and it's very long.Since it will be too complicated,i don't want to put inner class definition in root class.I mean how can i make a class inner without writing it in root class.

class outer
{

}

class inner
{

}

If i can use like that, The header file will be clearer i think.


回答1:


Like this:

// foo.hpp

class Foo
{
public:
  class Inner;
  Foo();
  void bar();
  Inner zoo();
};

// foo_inner.hpp

#include "foo.hpp"

class Foo::Inner
{
  void func();
};

Then, in the implementation:

#include "foo.hpp"
#include "foo_inner.hpp"

void Foo::bar() { /* ... */ }
void Foo::Inner::func() { /* ... */ }

Note that you can use the incomplete type Foo::Inner inside the class definition of Foo (i.e. in foo.hpp) subject to the usual restrictions for incomplete types, e.g. Inner may appear as a function return type, function argument, reference, or pointer. As long as the member function implementations for the class Foo can see the class definition of Foo::Inner (by including foo_inner.hpp), all is well.




回答2:


You can specify 'outer' as "public class outer", and put both its definition and the "inner" definition into a "class.java" file, and code in outer can instantiate inner just as if inner was in a different source file. It is not clear that is what you're after, because you have not explained why you want an "inner" class.



来源:https://stackoverflow.com/questions/8693590/how-to-make-an-inner-class-without-putting-the-definition-of-inner-class-to-pare

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