简体   繁体   中英

Creating class object in another class

I have created two class objects, each with a constructor and I am trying to make one class object a private variable in the other object. Here is a simple example of what I am trying to do, not the actual class names but an example. There are more public and private variables but just for simplicity sake I left them out. Each class has a separate .cpp and header file, and each header has the protectors (#ifndef, etc) So basically I have class tire with its private and public functions and variables, then I am trying to make class car with a private variable of type tire.

It will build without having tire object in car, but when I try to put tire MAKE into car i get these errors:

error C2146: syntax error : missing ';' before identifier 'A'
error C4430: missing type specifier - int assumed. Note: C++ does not support default-int

class tire{
    tire();
public:
    double a,b,c,d;
private:
    double e,f,g,h;
};

class car{
    car();
public:
    double i,j,k;
private:
    tire MAKE;
};

EDIT: I have a separate header file called Includes.h where I include all header files for the project. Looks something like

#include <iostream>
#include <string>
#include "tire.h"
#include "car.h"

then in tire.h and car.h I have

#include "Includes.h"

Your problem is that you're including "includes.h" in tire.h as well. When compiling, tire.h is compiled first and the safeguards define _tire_h_ (or whaterver your safeguard is). When car.h is compiled, the tire class is not defined.

Remove includes.h from tire.h and that should compile fine. The key is that tire must exist in car.h:

#include tire.h

class car{
    car();
public:
    double i,j,k;
private:
    tire MAKE;
};

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