C++自定义类未被其他类识别

C++ Custom Class is not being recognized by other classes

本文关键字:其他 识别 自定义 C++      更新时间:2023-10-16

我有Road和Car类,它们在自己的.cpp和.h文件中。我在Car标题中包含Road类的.h文件。我使用Road类作为Car类中函数的参数。我在汽车类中有静态变量,我需要在道路类中访问。

编译器无法识别Car类中的Road类型,我不知道为什么。

Road.h

#ifndef ROAD_H
#define ROAD_H
#include <iostream>
#include "car.h"
using namespace std;
class Road
{
public:
  // class functions
private:
  // member variables
};
#endif

Car.h

#ifndef CAR_H
#define CAR_H
#include <iostream>
#include "road.h"
using namespace std;
class Car
{
public:
  // class functions
  void enter_a_road(Road& r1, const short left_pos);
private:
  // member variables
};
#endif

错误消息:

In file included from Road.h:11:0,
                 from Road.cpp:6:
Car.h:68:23: error: 'Road' has not been declared
     void enter_a_road(Road& r1, const short left_pos);
                       ^

您有一个循环依赖项。解决此问题的最快方法是使用正向声明。

#include <iostream>
using namespace std;
class Road;
class Car
{
public:
  // class functions
  void enter_a_road(Road& r1, const short left_pos);
private:
  // member variables
};

这是可以接受的,因为编译器不需要知道Road的内部结构就可以编译函数声明。

Road.h中可能也可以这样做,尽管我不知道为什么一开始就有include。