一、重载为一般函数
格式:返回类型 operator 运算符(参数列表)
struct Complex{//定义一个复数结构:包括实部与虚部两部分 double real;//实部 double imag;//虚部
};
Complex operator+(Complex c1,Complex c2){//对加法运算的重载:将运算符'+' 定义为两复数相加 Complex c;c.real=c1.real+c2.real;c.imag=c1.imag+c2.imag;return c;
}
ostream&operator<<(ostream&out,Complex c){out<<"("<<c.real<<"+"<<c.imag<<"i)";return out;
}
int main()
{Complex c1={1,2},c2={3,4},c3;//结构体变量的声明c3=c1+c2; cout<<c1<<"+"<<c2<<"="<<c3<<endl;
}
运行结果
二、重载为友元函数
需要访问类中的私有成员,则要将该重载函数在类中声明为友元类。
格式:friend 类型 重载函数名(参数);
#include<iostream>
using namespace std;
class Complex{//定义一个复数类包括实部与虚部两部分 private:double real,imag;public:Complex(double r=0,double i=0):real(r),imag(i){}friend Complex operator+(Complex c1,Complex c2);friend ostream&operator<<(ostream&out,Complex c);
};
Complex operator+(Complex c1,Complex c2){//对加法运算的重载:将运算符'+' 定义为两复数相加,需要对复数类的私有属性进行访问 Complex c;c.real=c1.real+c2.real;c.imag=c1.imag+c2.imag;return c;
}
ostream&operator<<(ostream&out,Complex c){//需要对复数类的私有属性进行访问,声明成友元类 out<<"("<<c.real<<"+"<<c.imag<<"i)";return out;
}
int main()
{Complex c1(1,2),c2(3,4),c3;c3=c1+c2; cout<<c1<<"+"<<c2<<"="<<c3<<endl;
}
三、重载为成员函数
直接声明为成员函数
#include<iostream>
using namespace std;
class Complex{//定义一个复数类包括实部与虚部两部分 private:double real,imag;public:Complex(double r=0,double i=0):real(r),imag(i){}Complex operator+(Complex c);//直接在类中声明重载运算符 friend ostream&operator<<(ostream&out,Complex c);
};
Complex Complex::operator+(Complex c){//定义重载运算符 return Complex (real+c.real,imag+c.imag);
}
ostream&operator<<(ostream&out,Complex c){//需要对复数类的私有属性进行访问,声明成友元类 out<<"("<<c.real<<"+"<<c.imag<<"i)";return out;
}
int main()
{Complex c1(1,2),c2(3,4),c3;c3=c1+c2; cout<<c1<<"+"<<c2<<"="<<c3<<endl;
}