2014-02-22 48 views
0

這是我的呼籲,隨着交易將文件保存爲我的遊戲試圖讓一些gobal變量的鏈接命令失敗

#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得是全球性的,所以我的函數main文件不必須調用很多的功能,這是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 << "\n\nDo you want to load an old save or a new save?\n\n1 = new save  2 = old save\n\n"; 

    int saveChoice; 
    cin >> saveChoice; 

    if (saveChoice == 1) { 
     ofstream file; 
     cout << "what would you like to name the new file? (one word please)\n\n"; 
     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 name\n\n"; 
      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... \n\nattempt to open a different save file?\n\n"; 
        cin >> rechoice; 
        file.close(); 
        } 
       } 
      } 
     } 
    } 
} 
}; 

它使一個新的文本文件,或選擇,所以當保存文件,但它讀取一個,太多,如果選擇的話,那麼我想我的變量:水平,武器,secondWeapon,itemslot1和itemslot2可供整個程序訪問,並且可編輯所以如果玩家升級,它可以改變

回答

0

您正在頭文件中定義一些全局對象(level,weapon等)。這打破了一個定義規則。包含此頭文件的任何.cpp文件都將具有其自己的這些變量的定義。

合適的方法來處理這是使用extern頭文件聲明的對象,然後提供在一個單一的.cpp文件定義。也就是說,你的頭應該包含:

extern int level, weapon, secondWeapon; 
extern int itemslot1, itemslot2; 

然後你就會有這樣的一個.cpp文件:

int level, weapon, secondWeapon; 
int itemslot1, itemslot2; 
+0

然後將這些價值觀通過執行我的計劃 –

+0

@Bob_the_rhino沒錯。包含標題的任何文件都將能夠看到它們。 –

+0

謝謝,幫助很多! –