运算符重载
1.C++提供了单目运算符和二元运算符的重载,这样可方便同类成员函数对不同数据类型的操作,返回值操作类型也可能不同,
View Code
//add.hpp #ifndef _HHADD #define _HHADD class add { public: int temp; //int b; add() { temp=0; } }; #endif //addHPP.hpp #include "add.hpp" add operator+(add inputfi, int b) { return add(inputfi.temp+b); }; //main.cpp #include "add.hpp" #include "addFUN.hpp" #include <iostream> using namespace std; int main() { add output1(3),sum; //sum.b=output1.operator+(output2); sum=output1+8; cout<<"the sum of the results"<<sum.temp<<endl; return 0; }
1 class A 2 { 3 public: 4 int a; 5 int b; 6 int c; 7 A(): a(0), b(0),c(0) 8 {}//default constructor 9 A(int d, int e, int f):a(d),b(e),c(f) 10 {}//chongzai constructor 11 }; 12 A operator+(const A &ori) 13 { 14 a=a+ori.a; 15 b=b+ori.b; 16 c=c+ori.c; 17 return *this; 18 } 19 }; 20 int main() 21 { 22 A, output1,output2(10,20,30); 23 output1+=output2; 24 cout<<output1.a<<output1.b<<output1.c<<endl; 25 return 0; 26 }