编译player.cpp时无法识别player.hpp文件的问题排查
问题分析与修复方案
你遇到的编译错误主要来自头文件包含守卫的逻辑错误,再加上几个语法和参数匹配问题,下面逐个拆解修复:
1. 头文件包含守卫完全写反了
你的player.hpp里的包含守卫顺序搞反了:
#define PLAYER #ifndef PLAYER // ... 类定义 #endif
这个逻辑是先定义了PLAYER宏,然后检查如果PLAYER未定义才执行里面的代码,直接导致类定义的代码被完全跳过!正确的包含守卫应该是先检查宏是否未定义,再定义它:
#ifndef PLAYER #define PLAYER #include <string> #include <iostream> class Player { private: char symbol; std::string name; public: Player(char symbol, std::string name); std::string makeMove(); // 提示玩家输入要走的步骤 }; // 注意这里必须加分号! #endif
另外要注意:C++类定义的末尾}后面必须加分号,之前漏掉这一点也会触发编译异常。
2. 构造函数参数不匹配
你的头文件里声明的构造函数是Player(char symbol, std::string name);,但player.cpp里的实现只写了一个参数:
Player::Player(char symbol) { this->symbol = symbol; this->name = name; // 这里的name根本没有定义,因为参数里没传! }
必须改成和头文件声明一致的参数列表,用初始化列表实现会更规范:
Player::Player(char symbol, std::string name) : symbol(symbol), name(name) {}
3. 输入流操作符错误
player.cpp里的std::cin << playerMove;是错误的,输入操作应该用>>而不是<<:
std::cin >> playerMove;
4. 可选优化:补充cpp文件的头文件包含
虽然修复头文件后std::string的错误会消失,但养成好习惯:如果cpp文件里用到了某个标准库类型,最好在cpp里也包含对应的头文件,避免头文件修改后引发潜在问题。比如在player.cpp开头加上#include <string>。
修复后的完整代码
player.hpp
#ifndef PLAYER #define PLAYER #include <string> #include <iostream> class Player { private: char symbol; std::string name; public: Player(char symbol, std::string name); std::string makeMove(); // 提示玩家输入要走的步骤 }; #endif
player.cpp
#include "player.hpp" #include <string> // 可选,但推荐加上 Player::Player(char symbol, std::string name) : symbol(symbol), 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; }
现在再执行g++ -c player.cpp应该就能正常编译了。
内容的提问来源于stack exchange,提问作者Caleb Renfroe
相关产品推荐
相关产品推荐

