2014-03-13 85 views
0

我嘗試讀取團隊和玩家的一些數據並更改數據。 Player類成員有指向Team類的團隊的指針,而團隊有一個玩家列表,指向玩家的指針。複製矢量並保留成員的內存地址

問題出現在readin()函數中,該函數從txt.file中讀取團隊和玩家數據並返回一組隊列。在讀入過程之後,在讀入過程中創建的指針似乎指向錯誤的地址。

因此,從讀入函數返回的隊列向量中讀出數據與讀入函數中創建的指針中的數據不一樣。

這裏是類的一般structur:

#include <iostream> 
#include <vector> 
#include <string> 

class Player; 
class Team 
{ 
public: 
    std::vector<Player*> getplayerlist(){ 
     return playerlist; 
    } 
    void setteamname(std::string x){ 
     teamname = x; 
    } 
    std::string getteamname(){ 
     return teamname; 
    } 
    void Team::addPlayer(Player* x){ 
     playerlist.emplace_back(x); 
    }; 



private: 
    std::vector<Player*> playerlist; 
    std::string teamname; 

}; 

class Player 
{ 
public: 
    Team* getpteam(){ 
     return pteam; 
    } 
    void setpteam(Team* x){ 
     pteam = x; 
    } 
    void setinformation(std::string x, int y){ 
     name= x; 
     id = y; 
     } 

private: 
    int id; 
    std::string name; 
    Team* pteam; 
}; 

這裏是讀的功能

vector<Team> readin(){ 

//some readin stuff 

//if the line contains the teamname 

Team team; 
team.setteamID_(a); 
team.setteamname_(word2); 
Teamvector.emplace_back(team); 

//if the line contains player data 
//add the player to the team created before  

Player* player = new Player(); 
player->setinformation_(b, word1, lname, str, &Teamvector[a-1]); 
Teamvector[a-1].addPlayer(player); 

return Teamvector; 
} 

的結構,但如果我比較&Teamvektor[0]和地址

vector <Team> team = readin(); 
&team[0] 

他們是不同的。我如何「保持」儲存隊伍的地址?

回答

1

您按值返回std::vector:這意味着容器正在被複制,因此元素在內存中具有相同的值但地址不同。

如何處理這個問題的方法很少。例如:

  1. 創建容器,並在你的方法填充:

    std::vector<Team> v; 
    
    void readin_fillVector(vector<Team>& v) { 
        //.. v.push_back(team); 
    } 
    
  2. 遍迭代器

    void readin_fillVector(std::back_insert_iterator< std::vector<Team> > it) { 
        //.. (*it)++ = team; 
    } 
    
+0

我猜這就是問題所在,但could'nt圖出了如何解決這個問題。嘗試通過返回一個向量 insted但這也失敗了 – jimbo999

+0

我做了更改,但現在我得到錯誤C2664:'Team :: Team(const Team&)':無法將參數1從'Team *'轉換爲'const團隊&'\t \ xmemory0 \t 它來自線v.emplace_back(團隊)我想通了。編輯:我解決了它,在我的測試中將我的團隊改爲團隊*團隊。 Thx現在它的工作原理應該是 – jimbo999

+0

如果出現新問題,請使用新代碼和說明創建一個新問題 – 4pie0