1.友元函数方式为类重载运算符
(友元函数声明可以放在类任何地方)
1.类
class MM { public:MM() {}MM(int grade,string name):grade(grade),name(name){}friend MM operator+(MM object1, MM object2);void print() {cout << this->grade << this->name << endl;} private:int grade;string name; };
2.重载运算符函数编写
MM operator+(MM object1, MM object2) {MM object;object.grade = (object1.grade + object2.grade) / 2;object.name = object1.name;return object; }
3.main
int main() {MM object1(60,"小王");MM object2(80, "小王");MM object3 = object1 + object2;object3.print();return 0; }
结果:
2.使用成员函数实现重载运算符(使用this来减少传参)
1.class
class MM { public:MM() {}MM(int grade,string name):grade(grade),name(name){}MM operator+(MM object1);void print() {cout << this->grade << this->name << endl;} private:int grade;string name; };
2.实现函数
MM MM::operator+(MM object1) {MM object;object.grade = (object1.grade + this->grade) / 2;object.name = this->name;return object; }
3.main
int main() {MM object1(60,"小王");MM object2(80, "小王");MM object3 = object1 + object2;object3.print();return 0; }
结果:
3.对象的前置后置++
1.class
class MM { public:MM() {}MM(int size2, string name) :size2(size2), name(name) {}MM& operator++();MM& operator++(int);void print() {cout << this->name << "是" << size1 << "位用户,size2=" << this->size2 << endl;} private:static int size1;int size2=0;string name; }; int MM::size1 =0;
2.实现函数
(1)前置
MM& MM::operator++() {//前置++this->size1++;this->size2++;return (*this); }
精简版:
MM& MM::operator++() {//前置++this->size++;return (*this); }
(2)后置
MM& MM::operator++(int) {//后置++MM *object=new MM;object->name = this->name;object->size1 = this->size1;object->size2 = this->size2;this->size1++;this->size2++;return *object; }
精简版:
MM& MM::operator++(int) {//后置++MM *object=new MM;object->size = this->size;this->size++;return *object; }
3.main
int main() {//前置++MM mm1(10, "小爱");++mm1;mm1.print();//后置++MM mm2(10, "小洁");MM mm3=mm2++;//重点:实现函数中*object是赋值mm3mm3.print();//10mm2.print();//11return 0; }
结果: