复数类的实现

xiaoxiao2021-02-28  151

复数类的实现 先定义一个复数类,复数有虚部和实部,所以虚部和实部为类的私有成员,公有的有默认构造函数、拷贝构造函数、析构函数,运算符的重载等。

class Complex { public://4个默认成员函数 //默认构造函数 Complex(double real=0.0,double image=0.0) { _real= real; _image = image; } //拷贝构造函数 Complex(const Complex&c) { _real = c._real; _image = c._image; } //析构函数 ~Complex() { cout << "~Complex()" << endl; } //赋值操作符的重载 Complex& operator=(Complex& c)//赋值 { if (this != &c) { this->_real = c._real; this->_image = c._image; } return *this; } 重载的时候返回值用的是类的引用,其实这里也可以用void实现,在函数的内部已经改变了this的值,所以不用返回值。但是如果想要实现连等,连续赋值的情况,就得用返回值,返回值采用引用,比较高效。减少了副本的产生。 结果显示为:

加号的重载

Complex operator+(Complex& c)//加号重载 { this->_real = this->_real + c._real;//两个复数实部相加 this->_image = this->_image + c._image;//两个复数虚部相加 return *this; } Complex& operator+=(Complex& c)//+=号实现重载 { this->_real += c._real; this->_image += c._image; return *this; }

Complex operator-(Complex& c)//减号重载 { this->_real = this->_real - c._real;//两个复数实部相减 this->_image = this->_image -c._image;//两个复数虚部相减 return *this; } Complex & operator-=(Complex& c)//减号重载 { this->_real -= c._real; this->_image -= c._image; return *this; }

这里采用bool类型作为返回值,因为这里的返回值有两种,相等或者不9相等,主函数中已经给出了针对于返回值看是否相等。 bool operator==(const Complex& c)//相等重载 { if (this->_real == c._real) { if (this->_real == c._image) { return 1; } } else { return 0; } } bool operator!=(const Complex& c) { operator==(c); }

这里的前置++要注意的是,加之后this 的值改变,直接返回加之后this的值,而后置++不同,后置++返回的是没有+之前的this的值,这就需要先将this的值保存起来,之后返回即可。

Complex& operator++()//前置++ { this->_real++; this->_image++; return *this;//返回加之后的值 } Complex operator++(int)//后置++ { Complex tmp(*this);//后置++先保存当前值 this->_real++; this->_image++; return tmp;//返回当前值 }

前置++ 后置++

剩余功能及测试函数

void Display()//输出函数 { cout << _real << "+" << _image << "i" << endl; } private: double _real; double _image; };

主函数测试

int main() { int k = 0; Complex ret; Complex d1(5.2,4);//默认构造函数 d1.Display(); Complex d2(d1);//拷贝构造函数 d2.Display(); Complex d3; d3 = d2; d3.Display(); Complex d4(1.1, 2);//对+的重载 Complex d5(2.9, 3.0); k= (d4 == d5); if (k) { cout << "相等" << endl; } else { cout << "不相等" << endl; } /*d4 - d5; d4.Display(); d4 -= d5; d4.Display();*/ ++d4; d4.Display(); ret= (d4++); ret.Display(); return 0; }
转载请注明原文地址: https://www.6miu.com/read-19136.html

最新回复(0)