gpt4 book ai didi

C++类成员

转载 作者:太空宇宙 更新时间:2023-11-03 10:21:13 25 4
gpt4 key购买 nike

我是从 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 中,我能够毫无问题地执行类似的操作。有解决方案吗?谢谢...

最佳答案

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

// forward declaration
class Box;

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

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

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

box.h

class Table;

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

表.h

class Box;

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

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

box.cpp

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

表格.cpp

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

关于C++类成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4459894/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com