gpt4 book ai didi

c++ - 在 C++ 中创建另一个类中的类的对象

转载 作者:太空狗 更新时间:2023-10-29 23:50:34 25 4
gpt4 key购买 nike

我有一个类 ID3 和一个类树。 ID3 中使用了类 Tree 的对象,并显示未声明 Tree 的错误。

代码看起来像

#include <iostream>
#include <algorithm>
#include <cstdlib>
#include <math.h>
#include <vector>
using namespace std;
class ID3 {
public:
string v[];
int x;
public:
double Hi(Tree data)
{
int y=x-1;
}
};
class Tree{
Tree();
}

最佳答案

ID3中使用Tree之前需要前向声明,否则编译器不知道Tree是什么:

class Tree;

class ID3 {
...

如果您需要在某处使用 Tree实例,那么您需要在那之前获得 Tree 的完整定义,例如:

class Tree {
Tree();
};

class ID3 {
...
double Hi(Tree data) {
// do something with 'data'
int y=x-1;
}
};

有关何时使用前向声明的更多信息,请参阅 this Q&A .

关于c++ - 在 C++ 中创建另一个类中的类的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29051106/

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