3

私はこれを個人的な演習として行っていましたが、これが正しく、正しく理解されていることを確認したかったのです。行と列のメンバーを持つ座標クラスがあります。+および+=演算子をオーバーロードしたかったのです。これが私のコードです:

Coordinate& Coordinate :: operator+= (const Coordinate& rhs){
    this->m_Row += rhs.m_Row;
    this->m_Column += rhs.m_Column;

    return *this;
}

Coordinate& operator+ (const Coordinate& lhs, const Coordinate& rhs) {
    return Coordinate(lhs) += rhs;
}

どこ

friend Coordinate& operator + (const Coordinate& lhs, const Coordinate& rhs);

Coordinateクラスで定義されたフレンド関数です。

このコードに落とし穴はありますか?

これらがどのように機能するかについての私の理解は次のとおりです。

operator += 

rhsm_Rowとm_Columnをthisメンバーに追加します。を返し、reference to the object pointed by this pointerそれによってコピーコンストラクタによる別のオブジェクトの作成を回避します。

operator +

コピーコンストラクターを使用して(定数であり、その内容を変更したくないため)のローカルオブジェクトを作成しますlhs(これを呼び出します)。追加を実行するメンバー演算子を呼び出します。コピーコンストラクタが原因で別のオブジェクトが作成されないように、を返します。それ以外の場合は。lhslocalObj+=localObjreference to this localObj

ここで、ローカルオブジェクトへの参照を返すため、最後のステートメントが関係します。関数(演算子+)がスコープ外にlocalObjなるとすぐに破棄され、返される参照は破棄されたオブジェクトを指します。私はこれを理解するのに正しいですか?

もしそうなら、私はそれをどのように修正する必要がありますか?

編集: すべての答えと私が学んだことの後:これが私のCoordinateクラスが今どのように見えるかです:http://rextester.com/MJJI7394

4

2 に答える 2

6

あなたは心配する権利があります、あなたはここで一時的なものへの参照を返しています:

Coordinate& operator+ (const Coordinate& lhs, const Coordinate& rhs) {
    return Coordinate(lhs) += rhs;
}

Coordinateたとえば、次のように、値でaを返す必要があります。

Coordinate operator+ (Coordinate lhs, const Coordinate& rhs) {
    return lhs += rhs;
}

上記の例では、参照を取得して関数の本体にコピーする代わりに、最初のパラメーターのコピーを作成します。次に、その結​​果を値で返し+=ます。

この設定ではoperator+、友達として宣言する必要はありません。

詳細については、このSOリンクを参照してください。また、@Blastfurnaceに指摘していただきありがとうございます。

于 2012-08-11T17:51:14.160 に答える
0

個人的に、私はとの観点から定義しoperator+=()ます:operator+()operator=()

Coordinate operator+(const Coordinate& lhs, const Coordinate& rhs) {
  return Coordinate(lhs.getRow() + rhs.getRow(), lhs.getCol() + rhs.getCol();
}

const Coordinate& operator=(Coordinate& lhs, const Coordinate& rhs) {
  lhs.setRow(rhs.getRow());
  lhs.setCol(rhs.setCol());

  return lhs;
}

const Coordinate& operator+=(Coordinate& lhs, const Coordinate&rhs) {
  return lhs = lhs + rhs;
}

ここではセッターとゲッターを使用しています。または、フレンド機能やメンバー機能を使用することもできます。参照を返すすべての関数は、ローカルまたは一時オブジェクトへの参照に問題がないように、送信されたパラメーターを返すことに注意してください。

于 2012-08-11T18:11:56.193 に答える