简体   繁体   English

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

[英]Creating an object of a class in another class in C++

I have a class ID3 and a class Tree. 我有一个类ID3和一个类Tree。 An object of Class Tree is used in ID3 and its showing an error that Tree is not declared. 类树的对象在ID3中使用,并显示未声明树的错误。

Code looks like 代码看起来像

#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();
}

You need to forward declare Tree before using it in ID3 , otherwise the compiler doesn't know what Tree is: ID3使用之前需要转发声明Tree ,否则编译器不知道Tree是什么:

class Tree;

class ID3 {
...

If you need to use an instance of Tree somewhere then you need to have the full definition of Tree before that point, for example: 如果您需要在某处使用Tree实例 ,那么您需要在该点之前获得Tree的完整定义,例如:

class Tree {
    Tree();
};

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

For more information about when to use forward declarations, see this Q&A . 有关何时使用前向声明的更多信息,请参阅此问答

In general, C++ is compiled from top to bottom. 通常,C ++是从上到下编译的。 So if the class ID3 needs the class Tree, Tree must be defined before ID3. 因此,如果类ID3需要类Tree,则必须在ID3之前定义Tree。 Just put the class Tree before ID3 and it should be fine. 只需将类Tree放在ID3之前就可以了。

Forward deceleration of Tree will do the job. Tree前向减速将完成这项工作。 At the point where you used Tree instance in ID3 , the compiler knows nothing about your Tree class, compiling process goes from up to bottom. ID3使用Tree instance时,编译器对您的Tree类一无所知,编译过程从上到下。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM