/*
运算符<<的重载一直报错,
友原函数中可以访问到类的私有成员
*/
#include<iostream>
using namespace std;
class MyInt
{
private:
int m_i;
public:
friend void Printf(MyInt const &obj);
friend ostream operator<<(ostream &,MyInt const&);
MyInt(int i):m_i(i)
{
}
MyInt & operator++()
{
++(this->m_i);
return *this;
}
const MyInt operator++(int)
{
MyInt temp=*this;
++(*this);
return temp;
}
MyInt &operator--()
{
--(this->m_i);
return *this;
}
const MyInt operator--(int)
{
MyInt temp=*this;
--(*temp);
return temp;
}
MyInt &operator*()
{
return (MyInt&)m_i;
}
};
void Printf(MyInt const &obj)
{
cout<<obj.m_i<<endl;
}
ostream& operator<<(ostream &os,const MyInt &obj)
{
os<<'['<<obj.m_i<<']';
return os;
}
int main()
{
MyInt I(5);
cout<<I++;
cout<<++I;
cout<<I--;
cout<<--I;
cout<<*I;
Printf(I);
return 0;
}
/*
关于STL中仿函数的实现,用类(结构体)进行包装,但一定要是public类型,否则外部无法调用.语法有点怪异,实则是运算符的重载.
*/
#include <iostream>
using namespace std;
template<class T>
class plus
{
public:
T operator()(const T &x,const T &y)const
{
return x+y;
}
};
template <class T>
struct minus
{
T operator()(const T &x,const T &y)const
{
return x-y;
}
};
int main()
{
plus<int>plusObj;
minus<int> minusObj;
cout<<plusObj(3,5)<<endl;
cout<<minusObj(3,5)<<endl;
cout<<plus<int>()(43,50)<<endl;
cout<<minus<int>()(43,50)<<endl;
return 0;
/*
下面的语法可以通过语法检查,运行时指针未初始化,有点怪异。
*/
//int *p;
//new (p) int(2);
//cout<<"........."<<*p<<endl;
}
/*
一个简单Traits的实现
*/
#include <iostream>
using namespace std;
template<class T>
struct MyIter
{
typedef T value_type;
typedef T* p_value_type;
T *ptr;
MyIter(T* p=0):ptr(p){}
T& operator *()const
{
return *ptr;
}
};
template<class I>
typename I::p_value_type
funcp(I ite)
{
return &(*ite);
}
template<class I>
typename I::value_type
func(I ite)
{
return (*ite);
}
template <class I>
struct Iterator_traits
{
typedef typename I::value_type value_type;
};
template <class T>
struct Iterator_traits<T*>
{
typedef T value_type;
};
/*
template <class I>
typename iterator_traits<I>::value_type
function(I value)
{
return value;
}
*/
int main()
{
/*
myiter<int> ite(new int(8));
cout<<funcp(ite)<<endl;
cout<<func(ite)<<endl;
cout<<"-----------------------"<<endl;
*/
Iterator_traits<int *>::value_type a=12;
cout<<typeid(a).name()<<endl;
return 0;
}