C++中运算符的重载

来源:互联网 发布:购买地图数据要多少钱 编辑:程序博客网 时间:2024/06/05 14:38
#include<iostream>
using namespace std;
class Complex
{
public:
Complex (double real = 0 , double image = 0 );
// ~Complex();

Complex (const Complex& d);
Complex& operator= (const Complex& d);
void Display();

public:
friend ostream& operator<<(complex& out,complex& cmp);
Complex& operator++();
Complex operator++(int);
// Complex& operator--();
// Complex operator--(int); //后置--
//
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);

private:
double _real;// 实部
double _image;// 虚部
};
void Complex:: Display()
{
cout<<_real<<" "<<_image<<endl;
}
//Complex:: ~Complex()//析构函数
//{
// cout<<"调用析构函数"<<endl;
//}
Complex:: Complex (const Complex& d)// 拷贝构造函数
{
_real = d._real;
_image = d._image;
}
Complex& Complex:: operator= (const Complex& d)//赋值运算符重载
_real = d._real;
_image = d._image;
return *this;
}
Complex& Complex:: operator++()//前置加加运算符重载
{
++this->_real;
++this->_image;
return *this;
}
Complex Complex:: operator++(int)//后置加加运算符重载
{
Complex tmp;
tmp.-real = this->_real++;
tmp._image = this->_image++;
return tmp;
}
Complex Complex:: operator+(const Complex& c)//加号运算符重载
{
Complex tmp;
tmp._real = this->_real + c._real;
tmp._image = this->_image + c._image;
return tmp;
}
Complex& Complex::  operator-=(const Complex& c)//减等运算符重载
{
this->_real = this->_real - c._real;
this->_image = this->_image - c._image;
return *this;
}
Complex  Complex:: operator*(const Complex& c)//乘运算符重载
{
Complex tmp;
tmp._real = this->_real * c._real - this->_image * c._image;
tmp._image = this->_real * c._image + this->_real * c._real ;
return tmp;
}
Complex:: Complex(double real,double image)//带缺省值的构造函数
{
_real = real;
_image = image;
}
ostream& operator<<(complex& out,complex& cmp)
{
out<<cmp._real;
if(cmp._image>0)
out<<"+";
if(cmp._image != 0)
out<<cmp._image<<"i\n";
return out;
}
int main()
{

Complex c1(2,2);
Complex c2(4,4);
Complex c3(0,0);
c3 = c1 * c2;
c3.Display();
return 0;
}

0 0
原创粉丝点击