1

我从 Java 来到 C++ ......

当我尝试这样做时...

class Box {
    Table* onTable;
};

class Table {
    Box* boxOnIt;
};

int main() {
    Table table;
    Box box;

    table.boxOnIt = &box;
    box.onTable = &table;

    return 0;
}

编译器告诉我 Table 未定义。如果我切换类定义,编译器会告诉我 Box 未定义

在java中,我能够毫无问题地做这样的事情。有解决方案吗?谢谢...

4

7 回答 7

2

你应该使用前向声明。只需将此作为您的第一个声明:

class Table;  // Here is the forward declaration
于 2010-12-16T10:48:33.417 回答
2

在类 Box 之前添加:

class Table;

因此,您转发声明类 Table 以便可以在 Box 中使用指向它的指针。

于 2010-12-16T10:49:04.860 回答
2

你在这里有一个循环依赖,需要转发来声明其中一个类:

// forward declaration
class Box;

class Table
{
    Box* boxOnit;
}  // eo class Table

class Box
{
    Table* onTable
} // eo class Box

请注意,一般来说,我们有一个单独的头文件BoxTable,在两者中都使用前向声明,例如:

盒子.h

class Table;

class Box
{
    Table* table;
}; // eo class Box

表.h

class Box;

class Table
{
    Box* box;
};  // eo class Table

然后,在我们的实现 (.cpp) 文件中包含必要的文件:

盒子.cpp

#include "box.h"
#include "table.h"

表.cpp

#include "box.h"
#include "table.h"
于 2010-12-16T10:51:24.220 回答
1
class Table;

class Box {
    Table* onTable;
};

class Table {
    Box* boxOnIt;
};

int main() {
    Table table;
    Box box;

    table.boxOnIt = &box;
    box.onTable = &table;

    return 0;
}
于 2010-12-16T10:49:18.603 回答
1

您应该转发声明两个类之一:

class Table; // forward declare Table so that Box can use it.

class Box {
    Table* onTable;
};

class Table {
    Box* boxOnIt;
};

int main() {
    Table table;
    Box box;

    table.boxOnIt = &box;
    box.onTable = &table;

    return 0;
}

或相反亦然:

class Box; // forward declare Box so that Table can use it.

class Table {
    Box* boxOnIt;
};

class Box {
    Table* onTable;
};

int main() {
    Table table;
    Box box;

    table.boxOnIt = &box;
    box.onTable = &table;

    return 0;
}
于 2010-12-16T10:49:53.273 回答
1

使用前向声明,以便第一个声明的类知道第二个。 http://www.eventhelix.com/realtimemantra/headerfileincludepatterns.htm

于 2010-12-16T10:51:42.123 回答
0

在顶部添加类定义

class Table;

class Box {
    Table* onTable;
};

class Table {
    Box* boxOnIt;
};
于 2010-12-16T10:50:04.837 回答