#include<iostream>
using namespace std;
class Complex1
{
public:
Complex1(){real=0;imag=0;}
Complex1(double x,double y){real=x;imag=y;}
Complex1 complex_add(Complex1 &d);//普通方法实现加法
void print(){cout<<"("<<real<<","<<imag<<"i)\n";}
private:
double real;
double imag;
};
Complex1 Complex1::complex_add(Complex1 &d)
{
Complex1 c;
c.real=real+d.real;
c.imag=imag+d.imag;
return c;
}
class Complex2
{
public:
Complex2(){real=0;imag=0;}
Complex2(double x,double y){real=x;imag=y;}
Complex2 operator+(Complex2 &d);//操作符重载实现加法
void print(){cout<<"("<<real<<","<<imag<<"i)\n";}
friend std::ostream& operator<<(std::ostream &os,Complex2 &d);//操作符<<的重载。。效果类似于print()
private:
double real;
double imag;
};
//C++不允许用户自己定义新的运算符,只能对已有的运算符进行重载
//.(成员访问运算符)*(成员指针访问运算符)::(域运算符)sizeof(尺寸运算符)?:(条件运算符)不允许进行重载
//重载不能改变运算符操作数的个数;不能改变运算符的优先级别;不能有默认的参数
//重载的运算符必须和用户定义的自定义类型的对象一起使用,其参数至少应该有一个是类对象或类对象的引用(防止用户修改用于标准类型结构的运算符性质)
Complex2 Complex2::operator+(Complex2 &d)
{
Complex2 c;
c.real=real+d.real;
c.imag=imag+d.imag;
return c;
// return Complex2(real+d.real,imag+d.imag);
// return Complex2(this->real+d.real,this->imag+d.imag);
}
//operator<<()函数的原型是:std::ostram& operator<<(std::ostream& os,Rational f);
//第一个参数os是将要向它写数据的那个输出流;第二个参数f是打算写到输出流os里的数据值
//即将f写入os中
std::ostream& operator<<(std::ostream &os,Complex2 &d)
{
os<<"("<<d.real<<","<<d.imag<<"i)"<<endl;
return os;
}
class Complex3
{
public:
Complex3(){real=0;imag=0;}
Complex3(double x,double y){real=x;imag=y;}
friend Complex3 operator+(Complex3 &c,Complex3 &d);
void print(){cout<<"("<<real<<","<<imag<<"i)\n";}
private:
double real;
double imag;
};
//注意,这里作为友元函数,不属于Complex类,不要写::
Complex3 operator+(Complex3 &c,Complex3 &d)//友元函数,该函数不属于该类,但可以访问类的private、protected、public,即可以访问到c.real
{
return Complex3(c.real+d.real,c.imag+d.imag);
}
void main()
{
Complex1 c1(3,4),c2(5,-10),c3;
cout<<"使用普通方法实现加法:"<<endl;
c3=c1.complex_add(c2);
cout<<"c1=";c1.print();cout<<"c2=";c2.print();cout<<"c1+c2=";c3.print();//private成员不能通过类对象调用,只能通过成员函数print()调用
cout<<endl<<endl;
Complex2 c4(3,4),c5(5,-10),c6;
cout<<"使用运算符重载实现加法:"<<endl;
c6=c4+c5;
cout<<"c4=";c4.print();cout<<"c5=";c5.print();cout<<"c4+c5=";c6.print();
cout<<"使用操作符<<重载后c4+c5="<<c6;//操作符<<的重载
cout<<endl<<endl;
Complex3 c7(3,4),c8(5,-10),c9;
cout<<"使用友元函数实现加法:"<<endl;
c9=c7+c8;
cout<<"c7=";c7.print();cout<<"c8=";c8.print();cout<<"c7+c8=";c9.print();
cout<<endl<<endl;
}
C++——运算符重载
最新推荐文章于 2023-04-25 16:53:57 发布