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