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
Nested Class Definition in source file
提问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 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.
目前, 的定义MyClass
在CPP
文件中,而 的定义NestedClass
在头文件中,也就是说,我不能在CPP
文件中声明函数/构造函数。
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?
所以我的问题是,如何定义NestedClass
cpp 文件中的函数?如果我不能,原因是什么(如果是这种情况,我对为什么会发生这种情况有一个模糊的想法,但我想要一个很好的解释)?结构呢?
回答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.
};