【发布时间】:2013-02-17 15:21:33
【问题描述】:
我正在阅读 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 类的类型。
【问题讨论】:
-
从技术上讲,它是一个转换运算符。
标签: c++ operator-overloading operator-keyword