我在使用 MinGW C++ 组合涉及嵌套类的对象模型时遇到了问题。这是一个暴露我的问题的例子:
foo.h:
/*
* foo.h
*
* Created on: Sep 25, 2011
* Author: AutoBot
*/
#ifndef FOO_H_
#define FOO_H_
class Foo
{
public:
class Bar;
Bar bar;
} extern foo;
#endif /* FOO_H_ */
bar.h:
/*
* bar.h
*
* Created on: Sep 25, 2011
* Author: AutoBot
*/
#ifndef BAR_H_
#define BAR_H_
#include <iostream>
using namespace std;
#include "foo.h"
class Foo::Bar
{
public:
void Test() {cout <<"Test!";}
};
#endif /* BAR_H_ */
主要.cpp:
/*
* main.cpp
*
* Created on: Sep 25, 2011
* Author: AutoBot
*/
#include "foo.h"
Foo foo;
int main (int argc, char *argv[])
{
foo.bar.Test();
return 0;
}
Eclipse CDT 构建日志:
**** Build of configuration Debug for project NestedClassTest ****
**** Internal Builder is used for build ****
g++ -O0 -g3 -Wall -c -fmessage-length=0 -o src\main.o ..\src\main.cpp
In file included from ..\src\main.cpp:10:0:
..\src\/foo.h:15:6: error: field 'bar' has incomplete type
..\src\main.cpp: In function 'int main(int, char**)':
..\src\main.cpp:16:6: error: 'class Foo' has no member named 'bar'
Build error occurred, build is stopped
Time consumed: 171 ms.
所以本质上它无法识别我在 bar.h 中对 bar 的定义。这是正常的吗?为什么我不能以这种方式定义嵌套类?这仅仅是 MinGW 工具链的限制吗?感谢您提供任何帮助/建议。
旁注:在我的实际程序中,我打算将它的“foo”用作理论上的单例类。它将代表整个应用程序,并且它的子系统(或“条”)将在类内部定义和实例化一次。我这样做是为了让代码更易于管理。如果谁有更可行的设计模式,请告诉我!
最佳答案
问题出在这里:
class Foo
{
public:
class Bar;
Bar bar;
};
此时 Foo::Bar
是一个不完整的类型。并且您不能声明不完整类型的变量。这与尝试这样做没有什么不同:
class Foo;
Foo foo;
出于同样的原因,它们都是不允许的。
您可以将 bar
变成某种(智能)指针。但这是解决这个问题的唯一方法。
关于c++ - 为什么不能在外部定义嵌套类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7547655/