代码实例:
#include<iostream>
#include<cstdlib>
using namespace std;
template <typename T>
struct Plus
{
T operator()(const T& t1, const T& t2) const
{
return t1+t2;
}
};
template <typename T>
struct Minus
{
T operator()(const T&t1, const T& t2) const
{
return t1- t2;
}
};
class INT
{
public:
INT(int mi):_mi(mi){};
friend ostream& operator<<(ostream& os, const INT& Int);
INT& operator++() //increment and then fetch
{
++(this->_mi);
return *this;
}
INT operator++(int) //fetch and then increment
{
INT tmp = *this;
++(*this);
return tmp;
}
INT& operator--() //decrement and then fetch
{
--(this->_mi);
return *this;
}
INT& operator--(int) //
{
INT tmp = *this;
--(*this);
return tmp;
}
int& operator*() const
{
return (int&)_mi;
}
virtual ~INT()
{}
private:
int _mi;
};
ostream& operator<<(ostream& os, const INT& Int)
{
os << Int._mi << endl;
return os;
}
template<class T>
int fcmp(const void* elm1, const void* elm2)
{
const T* a = (const T*) elm1;
const T* b = (const T*) elm2;
if(*a-*b>0) return 1;
if(*a-*b == 0) return 0;
if(*a-*b < 0) return -1;
}
int main(int argc, char *argv[])
{
double ia[] = {12, 3, 25, 84,33.4, 56.9};
qsort(ia, sizeof(ia)/sizeof(double), sizeof(double), fcmp<double>);
for(int i=0; i<6;++i)
cout << ia[i]<<" ";
cout<<endl;
cout <<"-----------------------------------------------"<< endl;
INT Int(5);
cout<<Int++ <<endl;
cout << ++Int<<endl;
cout << Int--<<endl;
cout << --Int << endl;
cout << *Int << endl;
cout <<"-----------------------------------------------"<< endl;
Plus<int> plusobj;
Minus<int> minusobj;
cout << plusobj(35,10) << endl;
cout << minusobj(35, 10) << endl;
cout <<"-----------------------------------------------"<< endl;
return 0;
}