C++中重载运算符函数的方式:
以重载‘-’号为例,自定义为乘法。
第一种是直接在类内声明定义:(返回值是本类的对象)
#include <iostream> using namespace std; class test { public: test() {} test(int t1) { item = t1; } test operator-(test &t2) { this->item = this->item*t2.item; return *this; } void show() { cout << this->item; } private: int item; }; int main() { test t1(10); test t2(20); test t3 = t1 - t2; t3.show(); system("pause"); return 0; }
第二种是在类中声明为友元函数,类外定义,返回值的是一个类的对象。
#include <iostream> using namespace std; class test { public: test() {} test(int t1) { item = t1; } void show() { cout << this->item; } friend test operator-(test &t1, test &t2); private: int item; }; test operator-(test &t1, test &t2) { test t; t.item = t1.item*t2.item; return t; } int main() { test t1(10); test t2(20); test t3 = t1 - t2; t3.show(); system("pause"); return 0; }