2014-10-30 87 views
0

我有一個AdventureGame類,它有一個構造函數。當我嘗試做一個新AdventureGame對象,我收到錯誤消息「沒有匹配的函數調用‘AdventureGame :: AdventureGame()’嘗試實例化新對象時出錯

下面是我的一些類,構造函數,和主。

#include <iostream> 
#include <string> 
#include <fstream> 
using namespace std; 

class AdventureGame 
{ 
private: 
public: 
    int playerPos; 
    int ogrePos; 
    int treasurePos; 
    string location; 

    AdventureGame(int ogre, int treasure) 
    { 
     playerPos = -1; 
     ogrePos = ogre; 
     treasurePos = treasure; 
     location = ""; 
    }; 

. 
. 
. // other functions that I'm sure are irrelevant 
. 
. 

    int main() 
    { 
     AdventureGame game; 
     int numMoves = 0; 
     std::string move; 

     while (!game.isGameOver(game.playerPos)) 
     { 
      game.printDescription(game.playerPos); 
      cout << "Which direction would you like to move? (forward, left, or right)" << endl; 
      cin >> move; 
      game.move(move); 
      numMoves++; 
     } 
    } 

如何創建一個新的遊戲

+1

再次讀取錯誤。你在類中有一個顯式的構造函數,簽名爲'AdventureGame(intogog,intbauer)'。這將除去編譯器自動生成的默認構造函數。所以要麼你必須刪除顯式構造函數,或者在代碼中調用顯式構造函數而不是默認構造函數。看看:http://en.cppreference.com/w/cpp/language/default_constructor – nakiya 2014-10-30 05:05:05

回答

1

你的構造函數需要兩個參數,你需要通過他們

像這樣的實例:?

冒險遊戲遊戲(3,5);

0

您應該創建一個空的構造:

AdventureGame() 
{ 
    playerPos = -1; 
    ogrePos = 0; 
    treasurePos = 0; 
    location = ""; 
}; 

或總是創建類的傳球ogrePos和treasurePos值是:

AdventureGame game(0,0); 

也許是有道理的同時創建空的參數的構造函數。

0

您正在調用默認構造函數而未定義它。只需調用AdventureGame game;即可調用未定義的構造函數AdventureGame() {};。爲了打電話冒險遊戲(intogog,intbauer)在主函數中寫AdventureGame game (arg1, arg2)

如果您使用的是C++ 11,我建議最佳做法將始終使用AdventureGame game {}這種格式創建新對象。使用這種格式,AdventureGame game {}調用默認構造函數,AdventureGame game {arg1, arg2 ...}調用其他相應的構造函數。請注意0​​不會調用默認構造函數!

享受編碼!

0

Defualt構造缺少

AdventureGame() 
{ 
    playerPos = -1; 
    ogrePos = 0; 
    treasurePos = 0; 
    location = ""; 
} 
相關問題