复数
代码如下: (只写了一部分代码,其他懒得写,也没有使用模板类)
class Complex {
public:
double real, imag;
Complex(double real = 0, double imag = 0) {
this->real = real;
this->imag = imag;
}
Complex operator +(Complex c){
Complex res(real + c.real, imag + c.imag);
return res;
}
Complex operator -(Complex c) {
Complex res(real - c.real, imag - c.imag);
return res;
}
Complex operator * (Complex c) {
double new_real = (real * c.real - imag * c.imag);
double new_imag = (real * c.imag + imag * c.real);
Complex res(new_real, new_imag);
return res;
}
Complex operator ~ () {
Complex res(real, -imag);
return res;
}
friend ostream& operator << (ostream &out, Complex c) {
out << c.real;
if (c.imag > 0) {
out << '+';
}
if (c.imag != 0) {
out << c.imag << "im";
}
return out;
}
};
定义用其他函数生成该类的构造函数有利于这个类地更广泛地应用。