C++操作符operator的另一种用法

来源:互联网 发布:淘宝图片怎么拍摄 编辑:程序博客网 时间:2024/05/16 14:10

今天在程序员面试宝典上看到这样一道题目:

 A C++ developer wants to handle a static_cast<char*>() operation for the class String shown below. Which of the following options are valid declarations that will accomplish this task?

class String

{

public:

//...

//declaration goes here

};

 

A.    char* operator();

B.    char* operator char*();

C.    String operator char*();

D.    operator char*();

E.    char* operator String();

答案是D,但是百思不得其解,百度了很多资料,才发现原来operator的作用不仅仅在于运算符的重载,他还有另外一种作用:强制类型转换。

operator char*()是类型转换函数的定义,即该类型可以自动转换为char*类型。有时候经常和const在一起用,operator const char*() const.

下面看别人写的一个例子:

/*************************Test_OperatorConvert.h*************************/#ifndef TEST_OPERATORCONVERT_H#define TEST_OPERATORCONVERT_Hconst int MAX_PATH2 = 256;class Test_OperatorConvert{public:Test_OperatorConvert();Test_OperatorConvert(char *str);virtual ~Test_OperatorConvert();char *GetStr();operator char*();private:char m_szTest[MAX_PATH2];};#endif/*************************Test_OperatorConvert.cpp*************************/#include "stdafx.h"#include "Test_OperatorConvert.h"#include <iostream>using namespace std;Test_OperatorConvert::Test_OperatorConvert(){memset(m_szTest, 0, sizeof(m_szTest));}Test_OperatorConvert::Test_OperatorConvert(char *str){strcpy(m_szTest, str);}Test_OperatorConvert::~Test_OperatorConvert(){}// 这个函数实现的功能与operator char*()的功能一致。char *Test_OperatorConvert::GetStr(){return m_szTest;}Test_OperatorConvert::operator char*(){return m_szTest;}int main(int argc, char* argv[]){    Test_OperatorConvert cTestInstance;    char *pTest1 = cTestInstance; // 这里就是operator char*()发挥作用的地方,                                                      // 类Test_OperatorConvert 被转换成char*类型。    char *pTest2 = cTestInstance.GetStr(); //如果没有实现operator char*(),使用这种方法也一样。    return 0;}
这类似于一种隐式类型转换,实现的语法格式就是 operator type_name().

在需要char*类型的时候,就可以用Test_OperatorConvert来代替。还有一点需要注意的就是:C++中有3中函数不需要返回类型:构造函数、析构函数、类型转换函数

前两个我们都知道不允许返回任何类型,甚至void类型,也不允许出现return,最后一个也不写返回类型,但是必须返回对应类型的值,即必须有return语句。 

参考资料:http://hi.baidu.com/jiangzhp/blog/item/4b484723c2c6a24cad34dea7.html

原创粉丝点击