您的位置:首页 > 编程语言 > C语言/C++

C++实现复数Complex

2017-09-23 21:20 337 查看
用C++实现一个简单的复数类,主要涉及四个默认成员函数:
(1)构造函数:在定义对象时初始化成员变量,函数名与类名相同,无返回值(void也不能有),对象实例化时系统自动调用

(2)拷贝构造函数:是一种特殊的构造函数,它由编译器调用来完成一些基于同一类的其他对象的构建及初始化。
(3)析构函数:析构函数并不是删除对象,而是在撤销对象的占用内存之前进行一些清理工作,函数运行结束时自动调用
(4)运算符重载:就是对已有的运算符重新进行定义,赋予其另一种功能,以适应不同的数据类型。
以下就是复数类函数的一些简单操作的程序代码:#include<iostream>
using namespace std;
class Complex
{
public:
Complex( double real = 0.0, double image = 0.0);//构造函数
Complex(const Complex& c);//拷贝构造函数
Complex& operator=(const Complex& c);//赋值运算符重载
Complex operator+(const Complex& c);//加法运算符重载
Complex operator-(const Complex& c);//减法运算符重载
Complex operator*(const Complex& c);//乘法运算符重载
Complex operator/(const Complex& c);//除法运算符重载
Complex operator+=(const Complex& c);//加等
Complex operator-=(const Complex& c);//减等
Complex operator*=(const Complex& c);//乘等
Complex operator/=(const Complex& c);//除等
void display();//打印
private:
double _real;//实部
double _image;//虚部
};
接下来就是具体的函数实现
void Complex::display()
{
cout << "(" << _real << "," << _image << "i)" << endl;
}

Complex::Complex(double real, double image)
{
_real = real;
_image = image;
}

Complex::Complex(const Complex& c)
{
_real = c._real;
_im
4000
age = c._image;
}

Complex& Complex::operator=(const Complex& c)
{
_real = c._real;
_image = c._image;
return *this;
}

Complex Complex::operator+(const Complex&c)
{
Complex c1;
c1._real = c._real + _real;
c1._image = c._image + _image;
return c1;
}

Complex Complex::operator-(const Complex&c)
{
Complex c1;
c1._real = _real-c._real;
c1._image = _image -c._image;
return c1;
}

Complex Complex::operator*(const Complex& c)
{
Complex c1;
c1._real = _real*c._real - _image*c._image;
c1._image = _image*c._real + _real*c._image;
return c1;
}

Complex Complex::operator/(const Complex&c)
{
Complex c1;
c1._real = (_real*c._real + _image*c._image) / (c._real*c._real + c._image*c._image);
c1._image = (_image*c._real - _real*c._image) / (c._real*c._real + c._image*c._image);
return c1;
}

Complex Complex::operator+=(const Complex& c)
{
return Complex(_real += c._real, _image += c._image);
}

Complex Complex::operator-=(const Complex &c)
{
return Complex(_real -= c._real, _image -= c._image);
}

Complex Complex::operator*=(const Complex &c)
{
return Complex(_real *= c._real, _image *= c._image);
}

Complex Complex::operator/=(const Complex &c)
{
return Complex(_real /= c._real, _image /= c._image);
}

int main()
{
Complex c1(2.0, 5.0);
Complex c2(3.0, 6.0);
Complex c3(c1);
Complex c4 = c1 + c2;
cout << "c4=";
c4.display();
Complex c5 = c1*c2;
cout << "c5=";
c5.display();
c2 += c1;
cout << "c2=";
c2.display();
c2 -= c1;
cout << "c2=";
c2.display();
c3 *= c1;
cout << "c3=";
c3.display();
c5 /= c1;
cout << "c5=";
c5.display();
system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: