C++基础面向对象测试异常:getCurrentHealth相关输出缺失
C++面向对象编程输出异常问题排查
代码实现
Actor类
头文件(Actor.h)
#pragma once #include <string> class Actor { private: void setName(std::string inputName); public: std::string name{}; Actor(std::string inputName = "Actor"); std::string getName(); };
实现文件(Actor.cpp)
#include "Actor.h" Actor::Actor(std::string inputName) { setName(inputName); } void Actor::setName(std::string inputName) { name = inputName; } std::string Actor::getName() { return name; }
Character类
头文件(Character.h)
#pragma once #include "Actor.h" class Character : public Actor { public: int maxHealth{}; int currentHealth{}; Character(std::string inputName = "Character", int inputHealth = 100); int getCurrentHealth(); };
实现文件(Character.cpp)
#include "Character.h" Character::Character(std::string inputName, int inputHealth) : Actor{inputName}, maxHealth{inputHealth}, currentHealth{inputHealth} { } int Character::getCurrentHealth() { return currentHealth; }
Player类
头文件(Player.h)
#pragma once #include "Character.h" class Player : public Character { public: Player(); };
实现文件(Player.cpp)
#include "Player.h" Player::Player(): Character{"Player", 200} { }
主函数(main.cpp)
#include <iostream> #include "Player.h" int main() { Player a{}; std::cout << "Actor name is: " + a.getName() << std::endl; std::cout << "Player health is: " + a.getCurrentHealth() << std::endl; return 0; }
问题描述
运行上述代码后,a.getName()能正常输出字符串"Player",但a.getCurrentHealth()相关内容完全无输出——不仅无法显示数值,连前缀语句"Player health is: "也未打印。
问题原因与解决方案
核心原因
问题出在这行代码:
std::cout << "Player health is: " + a.getCurrentHealth() << std::endl;
这里的"Player health is: "是C风格字符串(本质是const char*指针),而a.getCurrentHealth()返回的是int类型。C++中,const char*和int执行+操作时,不会做字符串拼接,而是把指针向后偏移int对应的字节数。
a.getCurrentHealth()返回200,相当于把字符串指针直接向后跳200个字节,原字符串长度远小于200,偏移后指针指向了内存无效区域,触发未定义行为,表现为无输出、乱码甚至程序崩溃。
而第一行"Actor name is: " + a.getName()能正常工作,是因为a.getName()返回std::string,该类型重载了+运算符,可以和C风格字符串直接拼接成新的std::string对象,再被std::cout正确输出。
修复方案
有三种简单有效的修复方式:
- 将
int转换为std::string后拼接:
std::cout << "Player health is: " + std::to_string(a.getCurrentHealth()) << std::endl;
- 拆分输出语句,让
std::cout自动处理类型转换:
std::cout << "Player health is: " << a.getCurrentHealth() << std::endl;
- 使用
std::stringstream做格式化输出(适合复杂场景):
#include <sstream> // ... std::stringstream ss; ss << "Player health is: " << a.getCurrentHealth(); std::cout << ss.str() << std::endl;
内容的提问来源于stack exchange,提问作者Aldrahn Anjos
相关产品推荐
相关产品推荐

