説明
は複雑なクラスComplexを定義し、演算子 "+"をオーバーロードするため、複素数の加算に使用できます。オーバーロード演算子は、メンバーやフレンドではない通常の関数として機能します。2つの複素数の合計を求めるプログラムを記述します。
入力
2つの複素数の
出力
複素数と
サンプル入力
3. 4
。5 -10
サンプル出力
(8.00、-6.00i)
の#include <iostreamの>
する#include <iomanip>
使用して名前空間STD;
クラスコンプレックス
{
パブリック:
コンプレックス();
コンプレックス(ダブルr、double i);
double get_real();
double get_imag();
void display();
private:
double real;
double imag;
};
Complex :: Complex()
{
return;
}
Complex :: Complex(double r、double i)
{
real = r; imag = i;
}
double Complex :: get_real()
{
return real;
}
double Complex :: get_imag()
{
return imag;
}
void Complex :: display()
{
cout << "(" << real << "、" << imag << "i)" << endl;
}
複雑な演算子+(Complex a、Complex b)
{
double i、j;
i = a.get_real()+ b.get_real();
j = a.get_imag()+ b.get_imag();
複素数c(i、j);
cを返す;
}
int main()
{
double real、imag;
cin >> real >> imag;
複雑なc1(実数、
cin >> real >> imag;
Complex c2(real、imag);
複雑なc3 = c1 + c2;
cout << setiosflags(ios :: fixed);
cout << setprecision(2);
c3.display();
0を返します。
}
説明
は複雑なクラスComplexを定義し、演算子 "+"をオーバーロードするため、複素数の加算に使用できます。計算に含まれる2つの計算は、クラスオブジェクトにすることも、1つを任意の順序の整数にすることもできます。たとえば、c1 + c2、i + c1、c1 + iはすべて正当です(iは整数、c1、c2は複素数です)。整数と複素数の合計である2つの複素数の合計を求めるプログラムを作成します。
入力
2つの複素数複素数
と整数
整数と複素数
出力
2つの複素数の合計、複素数と整数の合計、整数と複素数の合計。
サンプル入力
3 4 5 -10
3 4 5
5 3 4
サンプル出力
c1 + c2 =(8.00、-6.00i)
c1 + i =(8.00,4.00i)
i + c1 =(8.00,4.00i)
#include <iostream >
#include <iomanip>
using namespace std;
class Complex
{
public:
Complex()
{
real = 0;
imag = 0;
}
Complex(double r、double i)
{
real = r;
imag = i;
}
複雑な演算子+(複雑な&c2);
複雑な演算子+(int&i);
フレンドComplex operator +(int&、Complex&);
void display();
プライベート:
ダブルリアル。
ダブルイメージ;
};
Complex Complex :: operator +(Complex&c2)
{return Complex(real + c2.real、imag + c2.imag);}
Complex Complex :: operator +(int&i)
{return Complex(real + i、imag);}
複雑な演算子+ (int&i、Complex&c)
{return Complex(i + c.real、c.imag);}
void Complex :: display()
{cout << "(" << real << "、" << imag << " i) "<< endl;
} int main()
{
double real、imag;
cin >> real >> imag;
Complex c1(real、imag);
cin >> real >> imag;
Complex c2(real、imag);
cout << setiosflags(ios :: fixed);
cout << setprecision(2);
複雑なc3 = c1 + c2;
cout << "c1 + c2 =";
c3.display();
int i;
cin >> real >> imag;
cin >> i;
c3 = Complex(real、imag)+ i;
cout << "c1 + i =";
c3.display();
cin >> i;
cin >> real >> imag;
c1 = Complex(real、imag);
c3 = i + c1;
cout << "i + c1 =";
c3.display();
0を返します。
}