【问题标题】:operator keyword in c++C++中的运算符关键字
【发布时间】: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


【解决方案1】:

它是一个 conversion 运算符(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

【讨论】:

    【解决方案2】:

    它是一个强制转换运算符。

    当您写 (Other)game; 时(即您将游戏投射到 Other)。

    它将被调用。

    【讨论】:

      【解决方案3】:

      这是一个 C++ 强制转换运算符。它定义了如果将一个对象强制转换为 Other 类会发生什么。

      【讨论】:

      • 它是一个转换运算符!
      猜你喜欢
      • 1970-01-01
      • 2017-11-27
      • 2012-01-30
      • 1970-01-01
      • 1970-01-01
      • 2019-07-22
      • 1970-01-01
      • 2016-01-15
      • 2017-09-27
      相关资源
      最近更新 更多