简体   繁体   English

在另一个类中创建类对象

[英]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. 每个类都有一个单独的.cpp和头文件,每个头都具有保护器(#ifndef等),所以基本上,我有带其私有和公共函数以及变量的类轮胎,然后我试图使一个具有私有变量的类汽车类型的轮胎。

It will build without having tire object in car, but when I try to put tire MAKE into car i get these errors: 它会在没有轮胎物体进入汽车的情况下构建,但是当我尝试将MAKE轮胎放入汽车时,出现以下错误:

error C2146: syntax error : missing ';' 错误C2146:语法错误:缺少';' before identifier 'A' 在标识符“ A”之前
error C4430: missing type specifier - int assumed. 错误C4430:缺少类型说明符-假定为int。 Note: C++ does not support default-int 注意:C ++不支持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. 编辑:我有一个名为Includes.h的单独的头文件,其中包括该项目的所有头文件。 Looks something like 看起来像

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

then in tire.h and car.h I have 然后在tire.h和car.h中

#include "Includes.h"

Your problem is that you're including "includes.h" in tire.h as well. 您的问题是,您还在轮胎.h中包含“ includes.h”。 When compiling, tire.h is compiled first and the safeguards define _tire_h_ (or whaterver your safeguard is). 编译时,先编译tire.h,然后定义保护措施_tire_h_(或无论保护措施如何)。 When car.h is compiled, the tire class is not defined. 编译car.h时,未定义轮胎类。

Remove includes.h from tire.h and that should compile fine. 从tire.h中删除include.h,应该可以正常编译。 The key is that tire must exist in car.h: 关键是car.h中必须存在轮胎:

#include tire.h

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

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

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