2013-02-17 87 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