首页 > 其他 > 详细

关于operator void* 操作符

时间:2016-02-28 10:54:47      阅读:131      评论:0      收藏:0      [点我收藏+]

在《大规模C++程序设计》这本书中谈到了迭代器模式。

他提供了这样的一个迭代器的例子

技术分享

?

技术分享

?

这个for循环中判断终止的写法,有点意思,做一下记录。

这个地方的本质是这样的:C++ 编译器,将it 转换为 (void*)it 观察是否是非0值。

之所以能转换,是因为重载了 void* 操作符。

?

  • 用vs新建一个win32控制台工程
  • 代码如下,代码将无法编译

// 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;

}

?

会有错误提示如下

技术分享

?

  • 修改CTest

// 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)

?

  • 在实际应用中,当然不能像上述例子这样返回this,必须考虑,某个条件成立,返回非0值,否则返回0.

    ?

    此次,我们修改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++程序设计这本书所说,对于不了解类设计的人。理解起来比较费劲。

    因此要慎重考虑。

技术分享

关于operator void* 操作符

原文:http://www.cnblogs.com/songr/p/5224115.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!