Pointer-like classes像指针又像函数
智能指针概念:
一个类做出来像类又像指针
示例代码:
#pragma once
#ifndef __SHAREPOINTER__
#define __SHAREPOINTER__
template<class T>
class shared_ptr
{
public:
shared_ptr(T* p) : px(p) { }
T& operator*() const { return *px; }
T* operator->() const { return px; }
private:
T* px;
long* pn;
};
#endif // !__SHAREPOINTER__
智能指针做两件事情:
-
能够返回智能指针包裹对象的解引用(地址)
-
能够通过智能指针调用包裹对象的方法
示例代码:
struct Foo
{
void method(void) {return 0;}
}
shared_ptr<Foo> sp(new Foo); // 这样就创建了一根Foo类的指针
Foo f(*sp); // 调用的是shared_ptr头文件定义的operator*操作符重载方法,返回智能指针包裹对象的地址
sp->method(); // 调用Foo类里面的method()方法 -> 通过指针调用
迭代器
链表的设计:
节点示例代码:
#pragma once
#ifndef __LISTNODE__
#define __LISTNODE__
template <class T>
struct __list_node
{
void* prev;
void* next;
T data;
};
#endif // !__LISTNODE_
链表迭代器使用:
#pragma once
#ifndef __LISTITERATOR__
#define __LISTITERATOR__
template<class T, class Ref, class Ptr>
struct __list_iterator
{
typedef __list_node<T>* link_type;
link_type node;
T& operator*() const { return (*node).data; }
T* operator->() const { return&(operator*()); }
};
#endif // !__LISTOTERATOR__
function-like classes 仿函数
对()
操作符重载,对象可以接受()
所以称之为function-like classes
示例代码:
#pragma once
#ifndef __PAIR__
#define __PAIR__
template<class T1, class T2>
struct pair
{
T1 first;
T2 second;
pair() : first(T1()), second(T2()) {}
pair(const T1& a, const T2& b) : first(a), second(b) {}
};
template<class Arg, class Result>
struct unary_function
{
typedef Arg argument_type;
typedef Result result_type;
};
template<class Arg1, class Arg2, class Result>
struct binary_function
{
typedef Arg1 first_argument_type;
typedef Arg2 second_argument_type;
typedef Result result_type;
};
#endif // !__PAIR__
使用示例:
#pragma once
#ifndef __PAIRREALLY__
#define __PAIRREALLY__
template<class T>
struct identity : public unary_function<T, T>
{
const T&;
operator() (const T& x) const { return x; }
};
template<class Pair>
struct select1st : public unary_function<Pair, typename Pair::first_type>
{
const typename Pair::first_type&;
operator() (const Pair& x) const { return x.first; }
};
template<class Pair>
struct select2nd : public unary_function<Pair, typename Pair::second_type>
{
const typename Pair::second_type&;
operator() (const Pair& x) const { return x.second; }
};
#endif // !__PAIRREALLY__
unary_function
和binary_function
都是仿函数