c++ - 为什么不能在外部定义嵌套类?

标签 c++ mingw external definition nested-class

我在使用 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/

相关文章:

java - Netbeans 和外部配置文件

C++ 模板和友元声明

c++ - 名称后跟 '::' 必须是类或命名空间错误,即使 '::' 跟在类名之后

php - 在 CakePHP 2 中执行外部 PHP 脚本

arrays - 从 C# 到 F# : Pinned Array and Stringbuilder in external function called from F#

c - 如何使用代码块 13.12(mingw) 在 c 中使用 delay() 函数?

c++ - 没有命名类型

c++ - 将 QVariant 中的枚举转换为整数

c++ - 在部分排序的数组中查找元素

c - 为什么这个 SIMD 示例代码可以使用 minGW 进行 C 编译,但可执行文件无法在我的 Windows 计算机上运行?