如何在另一个自己创建的类的头文件中包含一个自己创建的类? [英] How to include a self-created class in another self-created class's header file?

查看:168
本文介绍了如何在另一个自己创建的类的头文件中包含一个自己创建的类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我创建了两个类:轮胎和汽车。

Say I have created two classes: Tires, and Car.

所以我有四个文件:Tires.cpp,Tires.h,Car.cpp,Car.h。

So I have four files: Tires.cpp, Tires.h, Car.cpp, Car.h.

Car构造函数将Tires作为其参数。但是我不确定如何将Car.h修改为包括Tires.h的

The Car constructor takes Tires as its parameter. But I am not sure how to modify Car.h to include Tires.h.

这是我到目前为止所做的(注意:它们在单独的文件)

Here's what I've done so far (note: they are in separate files)

Tires.h

#include <iostream>
using namespace std;

class Tires
{
private:
    int numTires;

public:
    Tires();
};

Tires.cpp

Tires.cpp

#include <iostream>
#include "Tires.h"
using namespace std;

Tires::Tires()
{
    numTires = 4;
}

Car.h

#include <iostream>
#include "Tires.h" 
using namespace std;

class Tires; // Tried taking out forward declaration but still didn't work

class Car
{
private:
    Tires tires;

public:
    Car(Tires);   // Edited. Thanks to Noah for pointing out.

};

Car.cpp

#include <iostream>
#include "Car.h"
#include "Tires.h"
using namespace std;

Car::Car(Tires _tires)
{
    tires = _tires;
}

谢谢

推荐答案

您的方法在这里看起来不错。

Your approach seems fine here.

标头包含其他标头时要记住的一件事是,您可能会发现需要包括 包括卫队:

One thing to keep in mind when headers include other headers is that you may find you need to include an include guard:

// At the start of Tires.h:
//

// Only delcare this stuff if this is the first time including Tires.h:
//
#ifndef __myproject_Tires_h__
#define __myproject_Tires_h__

class Tires
{
   // [snip]
};

// Close the #ifdef above...
//
#endif

这可以防止您声明 类轮胎{等。多次,应该恰好包含两次 Tires.h

This prevents you from declaring "class Tire {" et al. multiple times, should Tires.h happen to be included twice.

另一个是在<$ c中的这一行不需要$ c> Car.h :

class Tires;

如果要声明轮胎*,这可能很有用。 Tires& ,但要做下一步:

This may be useful if you want to have declarations of Tires* or Tires&, but to do what you did next:

class Car
{
private:
   Tires tires;

...需要轮胎为完整类型,其大小未知。等等。无论如何,已经通过 #include Tires.h 覆盖了该类。

... requires Tires to be a "complete type", for its size to be known, etc. You're already covered by that by having #include "Tires.h" anyway.

最后,有人认为在标头中包含 using 语句是一种不好的形式。通过引入 std 作为使用此标头的所有文件的全局命名空间,这种类型的命名空间得以中断。想象一下,如果每个标头都这样做了,并且对多个名称空间都这样做了。最终,这与没有名称空间之类的东西一样,并且发生冲突的可能性更高。

Lastly, some consider it bad form to have a using statement inside a header as you have done. This kind of breaks namespaces by bringing in std as a global namespace for all files that use this header. Imagine if every header did this, and did so for multiple namespaces. Eventually this becomes the same as there being no such thing as namespaces, and collisions are more likely.

这篇关于如何在另一个自己创建的类的头文件中包含一个自己创建的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆