所以我的 3 类如下:
class Weapon {
char* name;
Target target;
int hitStrength;
public:
Methods...
};
class Player {
char* name;
int level;
int life;
int strength;
Weapon weapon;
int location;
public:
Methods...
};
class Game {
int maxPlayers;
Player** players;
public:
Methods...
};
我在包含时遇到问题。
我有一个 main.cpp
文件,其中包含以下内容:
#include "Game.h"
#include <iostream>
using namespace std;
但是,当我尝试构建程序时出现以下错误:
In file included from C:\Users\Name\CLionProjects\Call Of Matam Duties\Player.h:8:0,
from C:\Users\Name\CLionProjects\Call Of Matam Duties\Game.h:8,
from C:\Users\Name\CLionProjects\Call Of Matam Duties\main.cpp:1:
C:\Users\Name\CLionProjects\Call Of Matam Duties\Weapon.h:30:12: error: 'ostream' does not name a type
friend ostream& operator<< (ostream& os, const Weapon& w);`
提及:
Player.cpp
包含Player.h
;
Weapon.cpp
包含Weapon.h
;
Game.cpp
包含Game.h
;
Game.h
包括Player.h
和Weapon.h
。
是否正确?
我该如何解决这个问题?
如果您需要更多信息,请告诉我。
最佳答案
您应该包括 <iostream>
在 Weapon.h
因为那是需要它的地方。每个头文件都应该可以自己编译,而不应该依赖于放在其他包含之后。
有一个很好的做法可以避免此类错误。你有 Player.cpp
包括 Player.h
; Weapon.cpp
包括 Weapon.h
; Game.cpp
包括 Game.h
.很好,但要确保第一个头文件 Player.cpp
包括是 Player.h
与所有其他头文件相同。如果该更改导致任何编译错误,则表明您的头文件是错误的,因为它们无法独立编译。
通过包含所需的头文件或添加前向声明 来修复这些错误。但是要小心,不要以包含循环结束,这是一个坏主意,通常可以通过前向声明来避免。
关于C++ #include 和 operator<< 重载错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51906190/