首页 > 代码库 > 重载操作符
重载操作符
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;}
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。