2013-02-17 62 views
0

我正在讀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

+0

從技術上講,這是一個轉換操作符。 – 2013-02-17 15:30:10

回答

2

它是一個轉換運算符(NOT轉換運算符)。無論何時您的代碼要求轉換Other,都將使用該運算符。您的代碼可以通過兩種方式調用轉換。一個轉換髮生在這樣的情況:

Game g; 
Game::Other o(g); // **implicit conversion** of g to Game::Other 

顯式轉換當你寫一個在你的代碼中出現:

Game g; 
Game::Other o(static_cast<Game::Other>(g)); // **explicit conversion** 
    // of g to Game::Other 
0

這是一個演員。

當你寫(Other)game;(即你投了一個遊戲Other)。

它會被調用。

0

這是一個C++鑄造操作符。它定義瞭如果一個對象被轉換到Other類,會發生什麼。

+0

這是一個轉換操作符! – 2013-02-19 14:21:48