C++运算符重载
对已经有的运算符重新进行定义,赋予其另一个种功能,以适应不同的数据类型
加号运算符重载
class Person{ public: int m_A; int m_B; }
可以自己写成员函数来实现两个对象相加
Person PersonAddPerson(Person &p){ Person temp; temp.m_A=this->m_A+p.m_A; return temp; } Person operator+(Person &p){ Person temp; temp.m_A=this->m_A+p.m_A; return temp; }
通过全局函数实现
Person operator+(Person &p1,Person &p2){ Person temp; temp.m_A=p1.m_A+p2.m_A; return temp; }
左移运算符重载
只能用全局运算符重载<<运算符
ostream & operator<<(ostream &cout,Person &p){ return cout; }
递增运算符重载
1.
分为重载前置和后置
2.
#include<iostream> using namespace std; class MyInteger{ friend ostream& operator<<(ostream &cout,MyInteger &myint); public: MyInteger() { m_Num=0; } MyInteger& operator++(){ //Ç°ÖÃ++ÔËËã·ûÖØÔØ m_Num++; return *this; } MyInteger& operator++(int){ //ºóÖÃ++ÔËËã·ûÖØÔØ m_Num++; return *this; } private: int m_Num; }; ostream& operator<<(ostream& cout,MyInteger &myint){ cout <<myint.m_Num; return cout; } int main(){ MyInteger myint; cout <<myint<<endl; //ûÓÐÖØÔØʱ£º[Error] no match for 'operator<<' (operand types are 'std::ostream {aka std::basic_ostream<char>}' and 'MyInteger') cout <<++myint<<endl; cout <<myint++<<endl; return 0; }
赋值运算符重载
#include<iostream> using namespace std; class Person{ public: Person(int age){ m_Age=new int(age); } ~Person(){ if(m_Age!=NULL){ delete m_Age; m_Age=NULL; } } int *m_Age; void operator=(Person &p){ if(m_Age!=NULL){ delete m_Age; m_Age=NULL; } m_Age=new int(*m_Age); } }; void test01(){ Person p1(19); Person p2=p1; cout <<"p1的年龄是:"<<*p1.m_Age<<endl; cout <<"p2的年龄是:"<<*p2.m_Age<<endl; } int main(){ test01(); system("pause"); return 0; }
关系运算符重载
#include<iostream> using namespace std; class Person{ public: string m_Name; int m_Age; Person(string name,int age){ m_Name=name; m_Age=age; } bool operator==(Person &p){ if(this->m_Name==p.m_Name&&this->m_Age==m_Age) return true; return false; } }; int main(){ Person p1("Peter",19); Person p2("Ben",20); if(p1==p2) cout <<"p1等于p2"<<endl; else cout << "p1不等于p2"<<endl; return 0; }
函数调用运算符重载
函数调用运算符()也可以重载
由于重载后使用方式非常像函数的调用,因此成为仿函数
仿函数没有固定写法,非常灵活
#include<iostream> using namespace std; #include<string> class Myprint{ public: void operator()(string test){ cout <<test<<endl; } }; int main(){ Myprint p; p("liwanzhou"); return 0; }