简体   繁体   中英

Creating an object of a class in another class in C++

I have a class ID3 and a class Tree. An object of Class Tree is used in ID3 and its showing an error that Tree is not declared.

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:

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:

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. So if the class ID3 needs the class Tree, Tree must be defined before ID3. Just put the class Tree before ID3 and it should be fine.

Forward deceleration of Tree will do the job. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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