.cpp文件在编译时看不到.h文件
我正在尝试为一个类编译一个单元,我已将其拆分为一个.hpp和.cpp文件。这些文件被称为player.hpp和player.cpp。
我使用了命令g++ -c player.cpp。
这是 player.hpp
#define PLAYER
#ifndef PLAYER
#include <string>
#include <iostream>
class Player
{
private:
char symbol;
std::string name;
public:
Player(char symbol, std::string name);
std::string makeMove(); // Prompts the player to input a move to make
}
#endif
这是 player.cpp
#include "player.hpp"
Player::Player(char symbol)
{
this->symbol = symbol;
this->name = name;
}
std::string Player::makeMove()
{
std::string playerMove;
std::cout << this->name << "'s turn.nPlease make your move (enter as number combination of row and column. ex: 13 = First row, third column)n";
std::cin << playerMove;
return playerMove;
}
这是输出
player.cpp:3:1: error: ‘Player’ does not name a type
3 | Player::Player(char symbol)
| ^~~~~~
player.cpp:9:6: error: ‘string’ in namespace ‘std’ does not name a type
9 | std::string Player::makeMove()
| ^~~~~~
player.cpp:2:1: note: ‘std::string’ is defined in header ‘<string>’; did you forget to ‘#include <string>’?
1 | #include "player.hpp"
+++ |+#include <string>
2 |
我的.hpp文件似乎没有被正确包含,为什么?
回答
在您的 中player.hpp,包含守卫中的行顺序不正确。它应该是:
#ifndef PLAYER
#define PLAYER