2015-12-10 36 views
2

我目前正在製作一個快速的基於文本的運動模擬器。到目前爲止,我有2個班級,Team and Player。我嘗試在一個球隊中製造一系列球員,也就是名冊。 (不知道如何去做,否則)。我嘗試製作一名球員,然後將他分配到名冊陣列中的第一名。它編譯得很好,但是當我運行這個程序時,我得到'分段錯誤'的錯誤,這個錯誤與我導致的內存錯誤有關,我相信。代碼可能不是最好的,如果我的代碼不是最優化的,那麼很抱歉。如果您對如何解決此問題有任何建議,請告訴我。謝謝。簡單運動仿真中的分割錯誤

#include <iostream> 
#include <string> 
#include <stdio.h> 
#include <vector> 

using namespace std; 

class Player { 
    public: 
    string playerName; 
    string playerAge; 
    string position; 
} players; 

class Team: public Player { 
    public: 
    string name; 
    Player roster[]; 
} teams; 

void teamCrocovia() { 
    Team crocovia; 
    crocovia.name = "ComArch Crocovia"; 
    Player cro1; 
    crocovia.roster[0] = cro1; // This is the segmentation fault. 
} 

int main() { 
    teamCrocovia(); 
    return 0; 
} 
+0

團隊不應該從玩家派生。 –

+0

請勿將「(已解決)」放在標題中。我們可以告訴答案何時被接受。 –

+0

好的,謝謝。對於那個很抱歉。 –

回答

3

你不能指望這樣的:

Player roster[];     // this is a zero-sized array 

是一個可變大小的數組(在C++中沒有這樣的事情),並添加元素,如:

crocovia.roster[0]    // out of bounds access 

使用std::vector代替:

std::vector<Player> roster;  // in Team 
crocovia.roster.push_back(cro1); // add player 

此外,我不明白爲什麼Team繼承自Player,並且您立即創建具有每個類的複數名稱的對象,這些名稱甚至未被使用。

+0

謝謝,如果我的代碼看起來真的「不好」,我很抱歉。 –

+0

你願意使用std :: vector顯示我的代碼的替換嗎?謝謝。我已經有了 –

+0

。 – LogicStuff

3

當你寫你不知道肯定數組的大小不同的代碼,您應該如果定義數組的大小,例如

Player roster[5]; 

, 你應該只把它聲明爲

Player *roster; 

和其他地方(最好是在課堂隊的構造函數)實際上 使其成爲一個數組,也許這樣

roster = new Player[k]; 

,其中k是球隊中你想要的球員人數。

此外,關於該

class Team: public Player 

我不認爲這是你想要的。 我不認爲你想宣佈Team is A Player。

+1

不要忘記清理... –

+1

謝謝你的回答。我會用矢量試着回答你的答案,但是謝謝你花時間回答。 –