急用!!求大神用C++编写如下程序:复数类模版程序设计.
展开全部
#include <iostream>
class Complex {
friend const Complex operator + (const Complex& a, const Complex& b);
friend const Complex operator - (const Complex& a, const Complex& b);
friend const Complex operator * (const Complex& a, const Complex& b);
friend std::ostream& operator << (std::ostream& os, const Complex& a);
public:
Complex(double r = 0, double i = 0) : real(r), imag(i) {}
private:
double real, imag;
};
const Complex operator + (const Complex& a, const Complex& b)
{
Complex temp;
temp.real = a.real + b.real;
temp.imag = a.imag + b.imag;
return temp;
}
const Complex operator - (const Complex& a, const Complex& b)
{
Complex temp;
temp.real = a.real - b.real;
temp.imag = a.imag - b.imag;
return temp;
}
const Complex operator * (const Complex& a, const Complex& b)
{
Complex temp;
temp.real = a.real * b.real - a.imag * b.imag;
temp.imag = a.real * b.imag + a.imag * b.real;
return temp;
}
std::ostream& operator << (std::ostream& os, const Complex& a)
{
os << a.real;
if (a.imag > 0)
os << '+';
if (a.imag != 0)
os << a.imag << 'i';
return os;
}
int main()
{
using namespace std;
Complex a(1.1, 2.2), b(3.3, 4.4), c(5.5, 6.6), d(7.7, 8.8);
cout << a << endl;
cout << b << endl;
cout << c << endl;
cout << d << endl;
cout << a * b + c - d << endl;
return 0;
}
class Complex {
friend const Complex operator + (const Complex& a, const Complex& b);
friend const Complex operator - (const Complex& a, const Complex& b);
friend const Complex operator * (const Complex& a, const Complex& b);
friend std::ostream& operator << (std::ostream& os, const Complex& a);
public:
Complex(double r = 0, double i = 0) : real(r), imag(i) {}
private:
double real, imag;
};
const Complex operator + (const Complex& a, const Complex& b)
{
Complex temp;
temp.real = a.real + b.real;
temp.imag = a.imag + b.imag;
return temp;
}
const Complex operator - (const Complex& a, const Complex& b)
{
Complex temp;
temp.real = a.real - b.real;
temp.imag = a.imag - b.imag;
return temp;
}
const Complex operator * (const Complex& a, const Complex& b)
{
Complex temp;
temp.real = a.real * b.real - a.imag * b.imag;
temp.imag = a.real * b.imag + a.imag * b.real;
return temp;
}
std::ostream& operator << (std::ostream& os, const Complex& a)
{
os << a.real;
if (a.imag > 0)
os << '+';
if (a.imag != 0)
os << a.imag << 'i';
return os;
}
int main()
{
using namespace std;
Complex a(1.1, 2.2), b(3.3, 4.4), c(5.5, 6.6), d(7.7, 8.8);
cout << a << endl;
cout << b << endl;
cout << c << endl;
cout << d << endl;
cout << a * b + c - d << endl;
return 0;
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询