0

私は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

4

3 に答える 3

2

これは変換演算子です (キャスト演算子ではありません)。コードが演算子への変換を呼び出すたびに使用されます。Otherコードで変換を呼び出す方法は 2 つあります。暗黙的な変換は、次のような状況で発生します。

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
于 2013-02-17T15:33:06.853 に答える
0

キャスト演算子です。

書くとき(Other)game;(つまり、ゲームを にキャストするときOther)。

と呼ばれます。

于 2013-02-17T15:24:06.780 に答える
0

これは C++ キャスト演算子です。オブジェクトがクラス Other にキャストされた場合に何が起こるかを定義します。

于 2013-02-17T15:24:18.837 に答える