0

同じクラスにある 2 つのオブジェクトを追加しようとしています。

クラスのプライベート セクションには、2 つのint変数があります。

class One {

private:
int num1, num2;
public:

    One operator+=(const One&); // - a member operator that adds another One object - to the current object and returns a copy of the current object
    friend bool operator==(const One&, const One&); // - a friend operator that compares two One class objects for equality
};

 One operator+(const One&, const One&);// - a non-friend helper operator that adds One objects without changing their values and returns a copy of the resulting One 

問題があるかどうかはわかりませopeartor+

One operator+(const One &a, const One &b){

One c,d,r;

c = a;
d = b;

r += b;
r += a;

return r;
}

上記のコードは間違っていると思いますが、b.num1のように使用しようとすると、コンパイルエラーが発生します

error: 'int One::num1' is private error: within this context

上記の関数はメンバー関数セクションにないため、 b->num1 も使用できません。

error: base operand of '->' has non-pointer type 'const One'

このように呼び込みますmain

Result = LeftObject + RightObject;

4

2 に答える 2

5

このメンバー関数を既に実装している場合:

One One::operator+=(const One&);

次に、非メンバー加算演算子を次のように実装できます。

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

これは、次のようにいくらか単純化できます。

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

このパターン (すべてのオペレーター/オペレーター割り当てのペアに適用できます) は、オペレーター割り当てバージョンをメンバーとして宣言します。プライベート メンバーにアクセスできます。オペレーターのバージョンを非フレンド非メンバーとして宣言します。これにより、オペレーターのどちらの側でも型の昇格が可能になります。

余談:+=メソッドは、コピーではなくへの参照を返す必要が*thisあります。したがって、その宣言は次のようになりますOne& operator+(const One&)


EDIT : 実際のサンプル プログラムは次のとおりです。

#include <iostream>
class One {
private:
  int num1, num2;

public:
  One(int num1, int num2) : num1(num1), num2(num2) {}
  One& operator += (const One&);
  friend bool operator==(const One&, const One&);
  friend std::ostream& operator<<(std::ostream&, const One&);
};

std::ostream&
operator<<(std::ostream& os, const One& rhs) {
  return os << "(" << rhs.num1 << "@" << rhs.num2 << ")";
}

One& One::operator+=(const One& rhs) {
  num1 += rhs.num1;
  num2 += rhs.num2;
  return *this;
}

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

int main () {
  One x(1,2), z(3,4);
  std::cout << x << " + " << z << " => " << (x+z) << "\n";
}
于 2012-06-27T15:34:27.243 に答える
1

が間違っている理由がわかりませんoperator+

#include <stdio.h>

class One {
    public:
        One(int n1, int n2): num1(n1),num2(n2) {}

    private:
        int num1, num2;
    public:
        One operator+=(const One& o) {
            num1 += o.num1;
            num2 += o.num2;
            return *this;
        }
        friend bool operator==(const One&, const One&); // - a friend operator that compares two One class objects for equality
        void print() {
            printf("%d,%d\n", num1, num2);
        }
};

One operator+(const One& a, const One& b) {
    One r(0,0);
    r += b;
    r += a;
    return r;
}

int main() {
    One a(1,2),b(3,4);
    One r = a + b;
    r.print();
}
于 2012-06-27T15:34:18.320 に答える