一个类模板和类运算符重载的小程序

来源:互联网 发布:smtp.qq.com 端口 编辑:程序博客网 时间:2024/05/16 10:10
#include <iostream>
#include <string>
using namespace std;


class CBook
{
public:
    CBook(string name, int n=0) : m_strName(name), m_nIndex(n) {}
    void SetIndex(int n)
    {
    m_nIndex = n;
    }
    int GetIndex()
    {
    return m_nIndex;
    }

public:
    int m_nIndex;

private:
    string m_strName;
};

template<class T>
class ref
{
public:
    ref(T *p) : ptr(p) {}
    T * operator++() { return ++ptr; }
    T & operator*() { return *ptr; }
    T * operator->() { return ptr; }
    T & incr()
    {
    ++ptr->m_nIndex;
    return (*ptr);
    }
    
private:
    T *ptr;
};


int main()
{
    CBook book1("want", 100);
    ref<CBook> rb(&book1);
    cout << "Id : " << rb->GetIndex() << endl;
    rb.incr();
    cout << "Id : " << rb->GetIndex() << endl;

    return 0;
}
原创粉丝点击