重载操作符
C++语法规定可以重载操作符,例如*和->。下面是一个例子:
class Screen{ public: Screen(int x, int y) { m_x = x; m_y = y; } int m_x; int m_y; }; template<class TYPE> class ThreadLocal{ public: ThreadLocal(TYPE &s) { ptr = &s; } TYPE& operator*() { return *ptr; } TYPE* operator->() { return ptr; } private: TYPE *ptr; }; int main(int argc, char* argv[]) { Screen s1(100, 60); ThreadLocal<Screen> ps(s1); printf("%d, %d\n%d, %d\n", (*ps).m_x, (*ps).m_y, ps->m_x, ps->m_y); return 0; }
重载操作符很容易与转换函数混淆,例如下面的例子:
class Screen{ public: Screen(int x, int y) { m_x = x; m_y = y; } int m_x; int m_y; }; template<class TYPE> class ThreadLocal{ public: ThreadLocal(TYPE &s) { ptr = &s; } operator TYPE*() { return ptr; } TYPE* operator->() { return ptr; } private: TYPE *ptr; }; int main(int argc, char* argv[]) { Screen s1(100, 60); ThreadLocal<Screen> ps(s1); printf("%d, %d\n%d, %d\n", (*ps).m_x, (*ps).m_y, ps->m_x, ps->m_y); return 0; }