运算符重载:
运算符重载的一般格式:
返回类型 operator运算符 (参数列表)
{
重载函数体;
}
5个运算符不能重载: 成员运算符. 成员指针运算符* 域运算符:: 条件运算符?: 空间计算运算符 sizeof
运算符重载的规则:
不允许定义新的运算符
不能改变该运算符操作对象的个数
不能改变该运算符的优先级别和结合性
应注意符合实际的需要,重载的功能应该与运算符原有的功能相似,避免没有目的的使用运算符重载
运算符重载为友元函数,声明的一般形式为:
friend 返回类型 operator运算符 (参数列表)
运算符重载为成员函数,声明的一般形式为:
返回类型 operator运算符 (参数列表)
代码实现:
#include<iostream> using namespace std; class Complex { public: Complex(int real,int image) {//带参构造函数 this->real=real; this->image=image; }; Complex() {//无参构造函数 }; // 作为友元函数方式实现 friend Complex operator+(const Complex &c1,const Complex &c2) { Complex c3; c3.real=c1.real+c2.real; c3.image=c1.image+c2.image; return c3; }; Complex operator+(const Complex &c2) { Complex c; c.real=this->real+c2.real; c.image=this->image+c2.image; return c; }; //输出<<运算符重载 friend ostream &operator<<(ostream &cout,const Complex &c) { cout<<c.real<<"+("<<c.image<<"i)"<<endl; return cout; }; //输入>>运算符重载 friend istream &operator>>(istream &cin,Complex &c) { cin>>c.real>>c.image; return cin; }; //实现前置自增运算符重载 Complex operator++() { this->real++; this->image++; return *this; }; //实现后置自增运算符重载 Complex operator++(int) { Complex temp=*this; this->real++; this->image++; return temp; }; //采用成员函数形式,实现赋值运算符重载 Complex operator=(const Complex &c) { Complex c1; c1.real=c.real; c1.image=c.image; return c; } // 作为友元函数方式实现 friend Complex operator+(const Complex &c1,const Complex &c2) { Complex c3; c3.real=c1.real+c2.real; c3.image=c1.image+c2.image; return c3; }; Complex operator+(const Complex &c2) { Complex c; c.real=this->real+c2.real; c.image=this->image+c2.image; return c; }; //输出<<运算符重载 friend ostream &operator<<(ostream &cout,const Complex &c) { cout<<c.real<<"+("<<c.image<<"i)"<<endl; return cout; }; //输入>>运算符重载 friend istream &operator>>(istream &cin,Complex &c) { cin>>c.real>>c.image; return cin; }; //实现前置自增运算符重载 Complex operator++() { this->real++; this->image++; return *this; }; //实现后置自增运算符重载 Complex operator++(int) { Complex temp=*this; this->real++; this->image++; return temp; }; //采用成员函数形式,实现赋值运算符重载 Complex operator=(const Complex &c) { Complex c1; c1.real=c.real; c1.image=c.image; return c; }; //作为友元函数方式实现 friend bool operator==(const Complex &c1,const Complex &c2) { if(c1.real==c2.real&&c1.image==c2.image) { return true; } return false; }; //成员函数重载方式实现 bool operator==(const Complex &c2) { if(this->real==c2.real&&this->image==c2.image) { return true; } return false; }; private: int image; int real; }; main() {//在主函数进行测试 Complex c1(2,-9),c2(2,6); Complex c3; c3=c1+c2;//隐式调用 c3=operator+(c1,c2);//友元函数的显式调用 c3=c1.operator+(c2);//成员函数重载的显式调用 cin>>c3; cout<<c3; Complex c4=c1; cout<<c4; bool b=(c1==c2); cout<<b<<endl; }