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

Lee*_*lla 2 c++ class subclass

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

代码看起来像

#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();
}
Run Code Online (Sandbox Code Playgroud)

eml*_*lai 6

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

class Tree;

class ID3 {
...
Run Code Online (Sandbox Code Playgroud)

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

class Tree {
    Tree();
};

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

有关何时使用前向声明的更多信息,请参阅此问答.