c++复习之重载运算符

c++复习之重载运算符

重载运算符是c++实现多态的方法之一(另外是虚函数动态绑定和函数名重载),需要好好掌握。

/* * Author: ktmzgl * Created Time: 2017/3/4 16:27:02 * File Name: F:\Vim\code\TryOperator.cpp */ #include <iostream> #include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> #include <algorithm> #include <string> #include <vector> #include <stack> #include <queue> #include <set> #include <time.h> using namespace std; const int maxint = -1u>>1; class Try { public: int a; string s; Try(){} Try(int aa,string ss):a(aa),s(ss){} friend istream & operator >>(istream & in , Try &t); friend ostream & operator <<(ostream & out,Try &t); Try operator +(const Try &t) { return Try(a+t.a,s+t.s); } friend bool operator <(Try &t1,Try &t2) ; }; istream & operator >>(istream & in , Try &t) { in>>t.a>>t.s; return in; } ostream & operator <<(ostream & out,Try &t) { out<<t.a<<" "<<t.s<<endl; } bool operator <(Try &t1,Try &t2) { return t1.a<t2.a; } int main() { Try tmp; cin>>tmp; cout<<tmp; Try tmp1(2,"ff"); Try tmp2=tmp+tmp1; cout<<tmp2; if(tmp<tmp2) cout<<"tmp小于tmp2"<<endl; return 0; }