私のコメントでは、私は2つの代替ソリューションを提案しましたが、サンプルコードを手にしながら、私は3番目のものを見つけました。
サンプルコード:
#include <iostream>
// Version 1: (return type fixed)
class Complex1 {
friend std::ostream& operator << (std::ostream &out, const Complex1 &c);
private:
int a;
public:
explicit Complex1(int a): a(a) { }
// operator + as member
Complex1 operator + (const Complex1 &c) const
{
return Complex1(a + c.a);
}
};
std::ostream& operator << (std::ostream &out, const Complex1 &c)
{
return out << c.a;
}
// Version 2: (two overloaded operators)
class Complex2 {
friend std::ostream& operator << (std::ostream &out, const Complex2 &c);
friend int operator+(const Complex2 &c, const Complex2 &d);
friend int operator+(int c, const Complex2 &d);
private:
int a;
public:
explicit Complex2(int a): a(a) { }
};
std::ostream& operator << (std::ostream &out, const Complex2 &c)
{
return out << c.a;
}
int operator+(const Complex2 &c, const Complex2 &d)
{
return c.a + d.a;
}
int operator+(int c, const Complex2 &d)
{
return c + d.a;
}
// Version 3: (implicit conversion with constructor)
class Complex3 {
friend std::ostream& operator << (std::ostream &out, const Complex3 &c);
private:
int a;
public:
Complex3(int a): a(a) { }
// operator + as member
int operator+(const Complex3 &c) const
{
return a + c.a;
}
};
std::ostream& operator << (std::ostream &out, const Complex3 &c)
{
return out << c.a;
}
// Check everything out:
using namespace std;
int main()
{
cout << "Version 1:" << endl;
{ Complex1 c1(3), c2(5), c3(2);
Complex1 c4 = c1 + c2 + c3;
cout << "c4: " << c4 << endl;
}
cout << "Version 2:" << endl;
{ Complex2 c1(3), c2(5), c3(2);
Complex2 c4 = Complex2(c1 + c2 + c3);
cout << "c4: " << c4 << endl;
}
cout << "Version 3:" << endl;
{ Complex1 c1(3), c2(5), c3(2);
Complex1 c4 = c1 + c2 + c3;
cout << "c4: " << c4 << endl;
}
cout << "done." << endl;
return 0;
}
あなたはideone上でコードをコンパイルして実行することができます。
Complex1
部材従って
Complex1 Complex1::operator + (const Complex1 &c) const;
、(C1 + C2)として固定演算子を提供+ C3が
(Complex1 × Complex1 → Complex1)&倍Complex1 →あります複合体1
Complex2
したがって非メンバー
int operator+(const Complex2 &c, const Complex2 &d);
int operator+(int c, const Complex2 &d);
ように、2つのオーバーロードされた演算子を提供して、C1 + C2が
あるComplex2 × Complex2 → INT
及び(C1 + C2) + c3は
です
INT × Complex2 → INT
Complex3
Iはint
を受け入れる非explicit
コンストラクタを提供した本質的な違いを持つ元のサンプルのような非常に類似しています。これは、コンパイラが必要に応じて変換演算子として使用することを意味します。
(適切なコンストラクタを使用すると、オペレータの問題はすぐには気づかれなかったでしょう。)
したがって、C1 + C2が
Complex3 × Complex3 → INT
及び(C1 + C2)であり+ C3は
(INT → Complex3)× Complex3 → INT
はいですあなたはできる。あなたは何がうまくいかないか説明する必要があります。 – Tas
オペレータの戻り値のタイプが正しくありません。 – George
'complex :: operator +()'は 'int'を返します。それで 'c1 + c2'がcomplex x complex - > intなので、'(c1 + c2)+ c3'はint x complex->です。 'complex :: operator +()'の戻り値を 'complex'に変更するか、2番目の' operator +(int、complex) 'が必要です。どちらのオプションも有効です。 – Scheff