0
点赞
收藏
分享

微信扫一扫

第十八讲 不同类(指针类/仿函数)—————面向对象高级开发

1 不同类

1.1 pointer-like class(仿指针)

重载*、->运算符函数。

#include 
#include

template <typename T>
class Share_ptr{
public:
Share_ptr(T* p):px(p){}
T& operator*() const{ return *px;}
T* operator->() const{return px;}
private:
T* px;
};

class A{

};

int main(){
Share_ptr<A> sp(new A);
A a(*sp);
return 0;
}

1.2 function-like class(仿函数)

重载函数调用操作符

#include 
#include

template <typename T>
struct identity{
const T&operator()(const T& x) const{
return x;
}
};

template <typename Pair>
struct select1st{
const typename Pair::first_type& operator()(const Pair& x) const{
std::cout<<"operator()";
return x.first;
}
};

int main(){
std::pair<int, int> aPair;
select1st<std::pair<int, int>>()(aPair);
return 0;
}


举报

相关推荐

0 条评论