在《大规模C++程序设计》这本书中谈到了迭代器模式。
他提供了这样的一个迭代器的例子
? |
?
这个for循环中判断终止的写法,有点意思,做一下记录。
这个地方的本质是这样的:C++ 编译器,将it 转换为 (void*)it 观察是否是非0值。
之所以能转换,是因为重载了 void* 操作符。
?
// operatorTest.cpp : 定义控制台应用程序的入口点。 // ? #include "stdafx.h" #include <iostream> using namespace std; class CTest { ? public: ? }; ? ? int _tmain(int argc, _TCHAR* argv[]) { ????CTest t; ? ????if (t) ????{ ????????cout<<"true"<<endl; ????} ? ????return 0; } |
?
会有错误提示如下
?
// operatorTest.cpp : 定义控制台应用程序的入口点。 // ? #include "stdafx.h" #include <iostream> using namespace std; class CTest { public: ? ????operator void*() ????{ ????????return this; ????} }; ? ? int _tmain(int argc, _TCHAR* argv[]) { ????CTest t; ? ????if (t) ????{ ????????cout<<"true"<<endl; ????} ? ????return 0; } |
问题就解决了。解决的原因如开头所述,编译器将 if(t) => if((void*)t)
?
?
此次,我们修改CTest,让返回值与成员有关。
// operatorTest.cpp : 定义控制台应用程序的入口点。 // ? #include "stdafx.h" #include <iostream> using namespace std; class CTest { public: ????int d_Value; ????CTest() ????{ ????????d_Value = 0; ????} ? ????operator void*() ????{ ????????if (d_Value < 100) ????????????return (void*)1; ????????else ????????????return (void*)0; //或者返回NULL ????} }; ? ? int _tmain(int argc, _TCHAR* argv[]) { ????CTest t; ? ????while(t) ????{ ????????cout<<"当前dvalue的值是:"<<t.d_Value++<<endl; ????} ? ????return 0; } |
?
重载操作符的使用,如大规模C++程序设计这本书所说,对于不了解类设计的人。理解起来比较费劲。
因此要慎重考虑。
原文:http://www.cnblogs.com/songr/p/5224115.html