c++ - 如何将一个自创建的类包含在另一个自创建的类的头文件中?

标签 c++ class header

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

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

Car 构造函数将 Tires 作为其参数。但我不知道如何将 Car.h 修改为 包括 Tires.h。

这是我到目前为止所做的事情(注意:它们位于单独的文件中)

轮胎.h

#include <iostream>
using namespace std;

class Tires
{
private:
    int numTires;

public:
    Tires();
};

轮胎.cpp

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

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

汽车.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.

};

汽车.cpp

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

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

谢谢

最佳答案

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

当 header 包含其他 header 时要记住的一件事是,您可能会发现需要包含 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

这会阻止您声明“class Tire {”等。多次,应该Tires.h碰巧被包含两次。

另一个是 Car.h 中的这一行不需要:

class Tires;

如果您想要 Tires* 的声明,这可能很有用。或Tires& ,但要执行下一步操作:

class Car
{
private:
   Tires tires;

...需要 Tires成为一个“完整类型”,其大小已知等等。您已经通过 #include "Tires.h" 涵盖了这一点。无论如何。

最后,有些人认为 using 是一种不好的形式。正如您所做的那样,在标题中声明。这种通过引入 std 来破坏命名空间。作为使用此 header 的所有文件的全局命名空间。想象一下,如果每个 header 都这样做,并且对多个命名空间都这样做。最终这就像不存在命名空间这样的东西一样,并且更有可能发生冲突。

关于c++ - 如何将一个自创建的类包含在另一个自创建的类的头文件中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4502618/

相关文章:

c++ - GetTempPath() 写入的内存是否比发送的内存多?

c++ - 构建 vector 的递归函数,将返回什么?

c++ - 为什么传递临时特征表达式会导致访问未定义的内存?

python - 选择特定列仅在 Python 中形成数据框

c++ - 使用更多标准类型显式实例化给定模板函数的函数?

c++ - MAPI 可以信任不可变字符串吗?

class - 复制 Groovy 类属性

c++ - 多个文件包含到单个类冲突

python - python中的类和方法

java - 获取给定标题的网站的总 cookie 大小