C++回合制RPG开发中类生成的随机属性值跨作用域访问不一致问题
问题根源
- 变量作用域错误:第一个
if (answer == 1)块内定义的Thief player仅在当前块生效,块执行结束后对象就被销毁,后续逻辑无法访问该对象的存储值。 - 重复实例化对象:第二个
if (answer == 1)块内重新创建了全新的Thief对象,每次创建对象时都会触发类内的随机属性生成逻辑,得到的自然是全新数值。 - 类成员隐藏问题:子类
Thief重复定义了和父类Base同名的HP、ATK成员,会隐藏父类成员,导致属性赋值、读取逻辑混乱。 - 缺失必要头文件:使用
time()函数需要引入<ctime>头文件,否则部分编译器会报错。
修复代码
Finalh.h
#pragma once #include <iostream> using namespace std; // 基类 class Base { public: int newATK, newHP; int ATK, HP; // 添加虚析构函数,方便多态释放资源 virtual ~Base() = default; }; // 刺客子类 class Thief : public Base { public: Thief() { // 构造函数内生成随机属性,直接赋值父类成员 HP = rand() % 21 + 60; // 等价于rand() % (80+1-60) +60 ATK = rand() % 21 + 20; newHP = HP; newATK = ATK; } };
Final.cpp
#include <iostream> #include <ctime> #include "Finalh.h" using namespace std; int main() { srand(static_cast<unsigned>(time(NULL))); int answer; Base* player = nullptr; // 基类指针,提升到全局作用域,可指向任意职业子类 cout << "Choose your fighter 1) Assassin 2) Tank 3) Knight" << endl; cin >> answer; if (answer == 1) { player = new Thief(); cout << "You have choosen assassin, he has HP " << player->HP << " and ATK " << player->ATK << endl; } // 后续可以扩展2、3对应的坦克、骑士子类逻辑 cout << "Press 1 to show HP" << endl; cin >> answer; if (answer == 1 && player != nullptr) { cout << "This is my HP " << player->HP << endl; cout << "This is my newHP " << player->newHP << endl; } // 释放堆内存 delete player; return 0; }
逻辑说明
修复后全程只会创建一次职业对象,随机属性仅在对象实例化时生成一次,跨代码块通过基类指针可以正常访问最初生成的属性值,不会再出现随机数重新生成的问题。后续扩展坦克、骑士职业时,只需要继承Base类,在构造函数内实现对应职业的属性生成逻辑即可。
内容的提问来源于stack exchange,提问作者Jblaze
相关产品推荐
相关产品推荐

