这是我的主文件,调用处理游戏保存文件的函数
#include <iostream>
#include <fstream>
#include "Menu.cpp"
using namespace std;
extern int level;
int main() {
extern int level;
MM_class MM_obj;
MM_obj.MM_func();
cout << level;
}
我希望我的MM_class是全局的,这样我就不必调用很多函数,这是MM_class:
#include "Menu.h"
#include <iostream>
#include <fstream>
using namespace std;
int level, weapon, secondWeapon;
int itemslot1, itemslot2;
class MM_class{
public:
void MM_func() {
string saveName, saveInfo;
int rechoice = 1;
char gamename[] = "TBA";
cout << "Welcome to " << gamename << "nnDo you want to load an old save or a new save?nn1 = new save 2 = old savenn";
int saveChoice;
cin >> saveChoice;
if (saveChoice == 1) {
ofstream file;
cout << "what would you like to name the new file? (one word please)nn";
cin >> saveName;
file.open(saveName);
file << "11100";
level, weapon, secondWeapon = 1;
itemslot1, itemslot2 = 0;
file.close();
}
else {
if (saveChoice == 2) {
while (rechoice == 1) {
ifstream file;
cout << "please enter the save namenn";
cin >> saveName;
file.open(saveName);
if (file.is_open()) {
cout << "save successfully opened!n";
int getInfo = 0;
int saveInfo[5];
extern int level, weapon, secondWeapon;
extern int itemslot1, itemslot2;
while (getInfo != 4) {
file >> saveInfo[getInfo];
getInfo++;
}
level = saveInfo[0];
weapon = saveInfo[1];
secondWeapon = saveInfo[2];
itemslot1 = saveInfo[3];
itemslot2 = saveInfo[4];
rechoice = 0;
file.close();
}
else {
if (!file.is_open()) {
cout << "file could not be opened... nnattempt to open a different save file?nn";
cin >> rechoice;
file.close();
}
}
}
}
}
}
};
它会创建一个新的文本文件,或者在选择时保存文件,但如果选择这样做,它也会读取一个,所以我希望我的变量:级别、武器、第二武器、itemslot1 和 itemslot2 可以被整个程序访问,并且可以编辑,以便如果玩家升级,它可以更改
你在头文件中定义了一些全局对象(level
、weapon
等)。这打破了一个定义规则。包含此标头的任何.cpp
文件都将具有其对这些变量的自己的定义。
处理此问题的适当方法是使用 extern
声明头文件中的对象,然后在单个.cpp
文件中提供定义。也就是说,您的标头应包含:
extern int level, weapon, secondWeapon;
extern int itemslot1, itemslot2;
然后你会把它放在一个.cpp
文件中:
int level, weapon, secondWeapon;
int itemslot1, itemslot2;