C++:Headers相互包含会导致错误"class has not been declared"
C++ : Headers Including each others causes an Error "class has not been declared"
我对 C++ 比较陌生,整天都在面对这个问题,这真的很烦人。
假设我在单独的文件中有这 2 类
a.hpp :
#ifndef A_H
#define A_H
#include "d.hpp"
#include <iostream>
class CPlay
{
public:
CPlay() = default;
CPlay(int m_money) { money = m_money;}
void gameOn(int m_money, CRoom &a)
{
std::cout << "test";
}
~CPlay() {}
private:
int money;
};
#endif
和d.hpp:
#ifndef D_H
#define D_H
#include <iostream>
#include "a.hpp"
class CRoom
{
public:
CRoom() = default;
CRoom(std::string m_Name , short m_Seats)
{
Name = m_Name;
Seats = m_Seats;
}
void gameOff(int m_money , CPlay &a)
{
std::cout << "test2";
}
~CRoom() {}
private:
short Seats;
std::string Name;
};
#endif
在主程序中:
#include <iostream>
#include "a.hpp"
#include "d.hpp"
int main()
{
CRoom gameplay("GTA",5);
return 0;
}
我一直收到这个错误
d.hpp:13:31: error: 'CPlay' has not been declared
void gameOff(int m_money , CPlay &a)
我查看了一些文档并意识到这与 circular-dependency 有关,但我仍然无法解决问题。
我检查的一些问题单在 #define 和 #ifndef 方面有问题,但我这边的情况并非如此。
要打破循环依赖,你需要在每个头文件中添加依赖项的前向声明类,如下所示:
#ifndef A_H
#define A_H
#include <iostream>
class CRoom;
class CPlay {
...
和:
#ifndef D_H
#define D_H
#include <iostream>
class CPlay;
class CRoom {
...
请注意,这允许您从头文件本身中删除 #include
。
我对 C++ 比较陌生,整天都在面对这个问题,这真的很烦人。 假设我在单独的文件中有这 2 类 a.hpp :
#ifndef A_H
#define A_H
#include "d.hpp"
#include <iostream>
class CPlay
{
public:
CPlay() = default;
CPlay(int m_money) { money = m_money;}
void gameOn(int m_money, CRoom &a)
{
std::cout << "test";
}
~CPlay() {}
private:
int money;
};
#endif
和d.hpp:
#ifndef D_H
#define D_H
#include <iostream>
#include "a.hpp"
class CRoom
{
public:
CRoom() = default;
CRoom(std::string m_Name , short m_Seats)
{
Name = m_Name;
Seats = m_Seats;
}
void gameOff(int m_money , CPlay &a)
{
std::cout << "test2";
}
~CRoom() {}
private:
short Seats;
std::string Name;
};
#endif
在主程序中:
#include <iostream>
#include "a.hpp"
#include "d.hpp"
int main()
{
CRoom gameplay("GTA",5);
return 0;
}
我一直收到这个错误
d.hpp:13:31: error: 'CPlay' has not been declared
void gameOff(int m_money , CPlay &a)
我查看了一些文档并意识到这与 circular-dependency 有关,但我仍然无法解决问题。
我检查的一些问题单在 #define 和 #ifndef 方面有问题,但我这边的情况并非如此。
要打破循环依赖,你需要在每个头文件中添加依赖项的前向声明类,如下所示:
#ifndef A_H
#define A_H
#include <iostream>
class CRoom;
class CPlay {
...
和:
#ifndef D_H
#define D_H
#include <iostream>
class CPlay;
class CRoom {
...
请注意,这允许您从头文件本身中删除 #include
。