标签:复数类的比较及四则运算
问题描述:
创建一个Plural(复数)的class类,不借助系统的默认成员函数,在类体中写入构造函数,析构函数,拷贝复制函数以及运算符重载函数。并依次实现复数的大小比较(bool)和复数的四则运算(+,-,*,/)。
#include<iostream> using namespace std; class Plural { public: void Display() { cout << "Real->:" << _real; cout << " Image->:" << _image << endl; } public: Plural(double real = 1.0, double image = 1.0)//复数的实部和虚部存在小数情况,所以用double表示 { _real = real; _image = image; } Plural(Plural& a)//拷贝构造函数,注意引用符,若为值传递则可能会引发无穷递归 { _image = a._image; _real = a._real; } Plural& operator =(const Plural& c)//返回值可实现链式访问,不改变原有值,则加const修饰符 { if (this != &c) { this->_real = c._real; this->_image = c._image; } return *this; } ~Plural() { //cout << "析构函数" << endl; } bool operator >(const Plural& c); bool operator <(const Plural& c); bool operator ==(const Plural& c); Plural operator +(const Plural& c); Plural operator -(const Plural& c); Plural operator *(const Plural& c); Plural operator /(const Plural& c); private: double _real; double _image; }; //bool比较大小 bool Plural::operator >(const Plural& c)//this指针为隐指针,不可自己以参数方式传入,但可以直接使用; { return sqrt((this->_real)*(this->_real) + (this->_image)*(this->_image)) > sqrt((c._real)*(c._real) + (c._image)*(c._image)); } bool Plural::operator <(const Plural& c) { return !(*this>c); } bool Plural::operator ==(const Plural& c) { return sqrt((this->_real)*(this->_real) + (this->_image)*(this->_image)) == sqrt((c._real)*(c._real) + (c._image)*(c._image)); } //复数的四则运算 Plural Plural::operator+(const Plural &c)//相加 { Plural tmp; tmp._real = this->_real + c._real; tmp._image = this->_image + c._image; return tmp; } Plural Plural::operator-(const Plural &c)//相减 { Plural tmp; tmp._real = this->_real - c._real; tmp._image = this->_image - c._image; return tmp; } Plural Plural:: operator*(const Plural &c)// 复数的乘除较为复杂,因为相乘时存在i^2=-1此类的情况以及相除存在通分情况 { Plural tmp;//(a+bi)(c+di)=(ac-bd)+(bc+ad)i; tmp._real = (this->_real*c._real) - (this->_image*c._image); tmp._image = (this->_image*c._real) + (this->_real*c._image); return tmp; } Plural Plural:: operator/(const Plural &c) { Plural tmp;//(a+bi)/(c+di)=x+yi,x=(ac+bd)/(c*c+d*d),y=(bc-ad)/(c*c+d*d); tmp._real = ((this->_real*c._real) + (this->_image*c._image)) / (c._real*c._real + c._image*c._image); tmp._image = ((this->_image*c._real) - (this->_real*c._image)) / (c._real*c._real + c._image*c._image); return tmp; } //测试用例 void Test1() { Plural a, b(3, 5); a.Display(); b.Display(); cout << "Ret="<<(a < b) << endl; } //主函数 int main() { Test1(); return 0; }
注:初识类与对象,希望各位大牛不吝赐教。
本文出自 “温暖的微笑” 博客,请务必保留此出处http://10738469.blog.51cto.com/10728469/1734256
复数类的相关运算(判断大小及四则运算)->(构造,析构,拷贝复制,运算符重载)
标签:复数类的比较及四则运算
原文地址:http://10738469.blog.51cto.com/10728469/1734256