我正在讀C++思維。有一個我不明白的代碼片段。 任何人都可以幫我解釋一下嗎?運算符關鍵字在c + +中
class GameBoard {
public:
GameBoard() { cout << "GameBoard()\n"; }
GameBoard(const GameBoard&) {
cout << "GameBoard(const GameBoard&)\n";
}
GameBoard& operator=(const GameBoard&) {
cout << "GameBoard::operator=()\n";
return *this;
}
~GameBoard() { cout << "~GameBoard()\n"; }
};
class Game {
GameBoard gb; // Composition
public:
// Default GameBoard constructor called:
Game() { cout << "Game()\n"; }
// You must explicitly call the GameBoard
// copy-constructor or the default constructor
// is automatically called instead:
Game(const Game& g) : gb(g.gb) {
cout << "Game(const Game&)\n";
}
Game(int) { cout << "Game(int)\n"; }
Game& operator=(const Game& g) {
// You must explicitly call the GameBoard
// assignment operator or no assignment at
// all happens for gb!
gb = g.gb;
cout << "Game::operator=()\n";
return *this;
}
class Other {}; // Nested class
// Automatic type conversion:
operator Other() const {
cout << "Game::operator Other()\n";
return Other();
}
~Game() { cout << "~Game()\n"; }
};
在上面的代碼片段,我不明白:
operator Other() const {
cout << "Game::operator Other()\n";
return Other();
}
我想這個函數定義一個操作 「Other()
」。什麼意思是返回Other()
? 如果Other()
表示類別爲Other的對象,則運算符「Other()
」的返回類型不是類別Other
。
從技術上講,這是一個轉換操作符。 – 2013-02-17 15:30:10