//在实习3的Complex类基础上重载operator+、operator、operator+=、operator=、
//前置++和后置++运算符,Complex 的定义如下:
class Complex{
public:
Complex();
Complex(double r);
Complex(double r, double i);
Complex(const Complex& c);
~Complex();
void setValue(double r, double i);
double getReal() const ;
double getImage() const;
double getDistance() const;
void output() const;
Complex operator+(const Complex& f)const; Complex operator*(const Complex& f)const; Complex & operator+=(const Complex & f); Complex & operator*=(const Complex & f); Complex & operator ++(); //前置++,实部加 1 Complex operator++(int); //后置++,实部加 1 Complex add(const Complex& c)const;
Complex multiply(const Complex& c)const;
private:
double real;
double image; };
给出新增的函数定义。
Complex& Complex::operator=(const Complex& c) {
this->real = c.real;
this->image = c.image;
return *this;
}
Complex& Complex::operator+=(const Complex& f) {
this->real += f.real;
this->image += f.image;
return *this;
}
Complex Complex::operator+(const Complex& f) const {
return Complex(this->real + f.real, this->image + f.image);
}
Complex Complex::operator*(const Complex& f) const {
double r = this->real * f.real - this->image * f.image;
double i = this->real * f.image + this->image * f.real;
return Complex(r, i);
}
Complex& Complex::operator*=(const Complex& f) {
double r = this->real * f.real - this->image * f.image;
double i = this->real * f.image + this->image * f.real;
this->real = r;
this->image = i;
return *this;
}
Complex& Complex::operator++() {
this->real += 1;
return *this;
}
Complex Complex::operator++(int) {
Complex temp = *this;
this->real += 1;
return temp;
}
operator= 重载了赋值运算符,用于将一个 Complex 类型的对象赋值给另一个对象。
operator+= 重载了加等运算符,用于将一个 Complex 类型的对象与另一个对象相加,并将结果赋值给第一个对象。
operator+ 重载了加法运算符,用于将两个 Complex 类型的对象相加。
operator* 重载了乘法运算符,用于将两个 Complex 类型的对象相乘。
operator*= 重载了乘等运算符,用于将一个 Complex 类型的对象与另一个对象相乘,并将结果赋值给第一个对象。
operator++ 重载了前置自增运算符,用于将一个 Complex 类型的对象的实部加 1。
operator++(int) 重载了后置自增运算符,用于将一个 Complex 类型的对象的实部加 1,并返回自增前的对象。
findPrimeNumbers1(100)
/* [
5, 7, 11, 13, 17, 19, 23, 29,
31, 37, 41, 43, 47, 53, 59, 61,
67, 71, 73, 79, 83, 89, 97
]
*/
这里我们可以看到,逻辑没问题,能正常筛选出来。