作用:给运算符重新进行定义,赋予其另一种功能,以适应于不同的数据类型。
加号运算符重载“+”对于内置的数据类型,编译器知道如何进行运算。例如int a=10, int b=20, c=a+b这种的。若有两个对象相加,那怎么办呢?可以用加号运算符重载。
两个自定义数据类型相加的运算需要进行重载。
例:两个对象的相加。
case 1:通过成员函数实现两个对象的相加
#include#include using namespace std; class Person { public: Person PersonAddPerson(Person& p) { Person temp; temp.m_A = this->m_A + p.m_A; temp.m_B = this->m_B + p.m_B; return temp; } int m_A; int m_B; }; int main() { Person p1; p1.m_A = 10; p1.m_B = 10; Person p2; p2.m_A = 20; p2.m_B = 20; p2.PersonAddPerson(p1); cout << p2.m_A << endl; cout << p2.m_B << endl; }
case 2:成员函数重载+号运算符
成员函数重载本质的调用
Person p3=p1.operator+(p2);
#include#include using namespace std; class Person { public: //通过成员函数重载加号运算符 Person operator+ (Person& p) { Person temp; temp.m_A = this->m_A + p.m_A; temp.m_B = this->m_B + p.m_B; return temp; } int m_A; int m_B; }; int main() { Person p1; p1.m_A = 10; p1.m_B = 10; Person p2; p2.m_A = 20; p2.m_B = 20; Person p3 = p1 + p2; //等价于Person p3=p1.operator+(p2); }
case 3:全局函数重载+
全局函数重载的本质调用:Person p3=operator+(p1,p2);
#include#include using namespace std; class Person { public: int m_A; int m_B; }; //通过全局函数重载加号运算符 Person operator+ (Person& p1,Person& p2) { Person temp; temp.m_A = p1.m_A + p2.m_A; temp.m_B = p1.m_B + p2.m_B; return temp; } int main() { Person p1; p1.m_A = 10; p1.m_B = 10; Person p2; p2.m_A = 20; p2.m_B = 20; Person p3 = p1 + p2; }
对于内置的数据类型的表达式的运算符是不可以改变的,且不要滥用运算符重载。
左移运算符重载“<<”作用:配合友元,可以输出自定义的输出类型。
#include#include using namespace std; class Person { public: friend ostream& operator<< (ostream& cout, Person& p); Person(int a, int b) { m_A = a; m_B = b; } private: int m_A; int m_B; }; //利用全局函数重载左移运算符 ostream& operator<< (ostream& cout, Person &p) { //cout对象只能有一个,因此传个引用 cout << p.m_A << p.m_B; return cout; } void test01() { Person p(10,10); cout< 递增运算符重载“++”
作用:通过递增运算符,实现自己的整形数据。具体地,包括前置递增和后置递增。后置递增返回值,前置递增返回引用。
#includeusing namespace std; //重载递增运算符 //自定义整形 class MyInteger { public: MyInteger() { n_Num = 10; } friend ostream& operator<< (ostream& cout, MyInteger& myint); //重载++运算符(前置) MyInteger& operator++ () { //先进行++运算。再返回自己的引用,返回引用是为了一直对一个数据进行递增操作 n_Num++; return *this; } //重载++运算符(后置) MyInteger operator++ (int) //int的作用是代表占位参数,可以用于区分前置和后置递增 { //先记录当时的结果 MyInteger temp = *this; //后递增 n_Num++; //最后将记录结果返回,由于返回的是局部变量,因此不能返回引用 return temp; } private: int n_Num; }; ostream& operator<< (ostream& cout, MyInteger& myint) { cout << myint.n_Num; return cout; } void test01() { MyInteger myint; cout << ++(++myint)<< endl; } void test02() { MyInteger myint; cout << (myint++) << endl; } int main() { test02(); }



