2016-11-26 81 views
1

我有一個叫遊戲類,這是代碼的它的運算符=:操作=重載沒有工作,除非對象已初始化

Game& Game::operator=(const Game &other){ 
if(this==&other){ 
    return *this; 
}else{ 
    for(unsigned i=0;i<other.players.size();i=i+1){ 
     Player* copy; 
     int str= other.players.at(i)->getStr(); 
     if(str==1) 
      copy = new PlayerType1(dynamic_cast<const PlayerType1&>(*other.players.at(i))); 
     if(str==2) 
      copy = new PlayerType2(dynamic_cast<const PlayerType2&>(*other.players.at(i))); 
     if(str==3) 
      copy = new PlayerType3(dynamic_cast<const PlayerType3&>(*other.players.at(i))); 
     if(str==4) 
      copy = new PlayerType4(dynamic_cast<const PlayerType4&>(*other.players.at(i))); 
     players.push_back(copy); 
    } 
    winners = other.winners; 
    state = vector<string>(other.state); 
    deck = Deck(other.deck); 
    verbal = other.verbal; 
    highestNum = other.highestNum; 
    turnNum = other.turnNum; 
    currPlayer = other.currPlayer; 
    lastAsker = other.lastAsker; 
    lastAskee = other.lastAskee; 
    lastAskedCard = other.lastAskedCard; 
    return *this; 
} 

}

我嘗試在這裏稱之爲:

char* cf= "../src/config1.txt"; 
Game* game = new Game(cf); 
game->init(); 
Game game2=*game; 
game->play(); 
game2.printState(); 

在這種情況下,我的operator =不會被使用。 但如果GAME2已初始化,例如這裏:

Game* game = new Game(cf); 
game->init(); 
Game game2=*(new Game()); 
game2=*game; 
game->play(); 
game2.printState(); 

任何想法可能是什麼問題?

回答

1

在第一種情況下,copy elision可避免調用賦值運算符,以支持複製構造函數。

在第二種情況下,對象已經建好,所以必須調用賦值操作符。

結論是,您必須實現所有3個運算符:析構函數,賦值和複製(也稱爲rule of three),否則根據編譯器的不同,您可能會有不可預知的行爲。

,並避免不一致的方式實現他們的最好方法是使用copy & swap idiom

+0

謝謝:)這是問題! – Dolav