2013-04-30 282 views
-3

Player.h構造函數的參數

#ifndef HEADER_GUARD_PLAYER 
#define HEADER_GUARD_PLAYER 

#include <string> 
using std::string; 


//Parent player class 
class Player 
{ 
     private:   
     protected: 
     string playerName; 
     int chipCount; 

     public: 
     //Constructor 
     Player(); 
     Player(string name); 

}; 

//Custom Players 

class PlayerSteven: public Player 
{ 
}; 
class PlayerBlake: public Player 
{ 
}; 
class PlayerTucker: public Player 
{ 
}; 
#endif 

Player.cpp

#include "Player.h" 
#define STARTCHIPS 1500 

Player::Player() 
{ 
    chipCount = STARTCHIPS; 
    playerName = "Default";   
}; 
Player::Player(string name) 
{ 
    playerName = name; 
}; 

Main.cpp的

#include <iostream> 
#include "Deck.h" 
#include "Player.h" 
#include <string> 

using namespace std; 

int main() 
{ 
    Deck deck; 
    PlayerSteven steven = new PlayerSteven("Steven"); 
    PlayerBlake blake = new PlayerBlake("Blake"); 
    PlayerTucker tucker = new PlayerTucker("Tucker"); 

    deck.shuffle(); 
    int x = 0; 
    int y = 0; 
    for (int i = 0; i < 52; i++) 
    { 
     deck.nextCard(x,y); 
     cout << x << "," << y << endl; 
    } 
    system("PAUSE"); 
    return 0; 
} 

錯誤:

11 C:\用戶\文檔\ temp中\ p_comp.cpp沒有用於調用PlayerSteven :: Play的匹配函數erSteven(爲const char [7]) '

11 C:\用戶\文檔\ TEMP \ p_comp.cpp沒有匹配函數調用`PlayerSteven :: PlayerSteven(爲const char [7])'

音符C:\ Dev-Cpp \ PROJECTS \ Player.h:26 PlayerSteven :: PlayerSteven(const PlayerSteven &)

任何人都知道我可以得到這個編譯?

謝謝。

+0

你試過了什麼? – djechlin 2013-04-30 14:43:28

+2

爲什麼你讓你的「自定義球員」強壯的類型?它們與基礎'Player'類沒有什麼不同,並且你沒有做任何與需要的類型相關的特定任何東西。例如,正確的方法是實例化實際類型,即Player Steven(「Steven」)。 – Chad 2013-04-30 14:46:09

+0

@djechlin:你什麼意思?他試圖編譯這個問題中的代碼。 – 2013-04-30 14:47:01

回答

2

在C++構造函數中沒有繼承。所以,你必須將它們添加在子類:

class PlayerSteven: public Player 
{ 
public: 
    PlayerSteven() 
    {} 
    PlayerSteven(string name) 
    :Player(name) 
    {} 
}; 

與同爲中Player其他子類。

如果你有一個足夠新的C++編譯器11實際上你可以繼承構造函數,但你必須這樣做明確:

class PlayerSteven : public Player 
{ 
public: 
    using Player::Player; 
}; 
+0

在C++ 11中,使用Player :: Player應該就足夠了(顯然,在支持它的編譯器上)。 – mfontanini 2013-04-30 14:41:36

+0

好吧我添加了每個子類的構造函數,但是我收到了新錯誤:從'PlayerSteven'轉換爲非標量類型'PlayerSteven'請求 – Steven 2013-04-30 14:54:15

+0

@Steven:是的,與前一個無關,並暗示在@Chad刪除的答案中。這是C++,而不是Java或C#:不寫'PlayerSteven steven = new PlayerSteven(「Steven」);',只是'PlayerSteven steven(「Steven」);'或者如果你需要它是動態的:'PlayerSteven * steven = new PlayerSteven(「Steven」);',但你必須在某處刪除它。 – rodrigo 2013-04-30 15:02:24

1

您需要聲明並定義爲派生類型構造函數:

class PlayerSteven: public Player 
{ 
    PlayerSteven() {} 
    PlayerSteven(const std::string& s) : Player(s) {} 
}; 

等等。在C++ 11中,您可以使用inherited constructors

class PlayerSteven: public Player 
{ 
    using Player::Player; 
}; 

接下來,在你的主,你正試圖從一個指針PlayerSteven對象初始化爲PlayerSteven

PlayerSteven steven = new PlayerSteven("Steven"); 

你沒有構造函數來執行這樣的轉換,這你可能不無論如何。你可以實例化一個PlaverSteven對象:

PlayerSteven steven("Steven");