2010-02-10 91 views
12

我有一个类下面的代码:运算符string(){some code}做什么?

operator string() { 
     return format("CN(%d)", _fd); 
} 

,想知道该运营商做什么。

我熟悉常用的字符串操作符:

bool operator==(const string& c1, const string& c2); 
bool operator!=(const string& c1, const string& c2); 
bool operator<(const string& c1, const string& c2); 
bool operator>(const string& c1, const string& c2); 
bool operator<=(const string& c1, const string& c2); 
bool operator>=(const string& c1, const string& c2); 
string operator+(const string& s1, const string& s2); 
string operator+(const Char* s, const string& s2); 
string operator+(Char c, const string& s2); 
string operator+(const string& s1, const Char* s); 
string operator+(const string& s1, Char c); 
string& operator+=(const string& append); 
string& operator+=(const Char* append); 
string& operator+=(const Char append); 
ostream& operator<<(ostream& os, const string& s); 
istream& operator>>(istream& is, string& s); 
string& operator=(const string& s); 
string& operator=(const Char* s); 
string& operator=(Char ch); 
Char& operator[](size_type index); 
const Char& operator[](size_type index) const; 

...但没有这一项?

回答

29
operator Type() { ... } 

是(隐含的)转换运算符。例如,如果类Animal实现operator string(),那么代码

Animal a; 
... 
do_something_with ((string)a); 

将成为像

do_something_with ((Animal::operator string)(&a)); 

一些更多的例子见http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/index.jsp?topic=/com.ibm.xlcpp8a.doc/language/ref/cplr385.htm

+1

+1用于指定它的专有名称,转换运算符。 – 2010-02-10 18:40:38

+0

一个很好的例子是经常使用的'operator bool(){...}',它允许一个类型的对象用在'if(object){...} else {...}'中,例如在容器类型中可以实现为真正意义上的非空。 – wich 2010-02-10 18:49:03

+0

@wich:'运营商布尔'可以给你意想不到的行为http://stackoverflow.com/questions/2145931/why-is-operator-bool-invoked-when-i-cast-to-long。 – kennytm 2010-02-10 18:56:35

1

如果只是返回当前对象的字符串重新抑制,例如用于在控制台上打印。

+1

更具体地说,它是转换为“string”类型的转换运算符。您也可以创建针对其他类型的转换运算符。 – 2010-02-10 18:38:50

7

它重载了演员操作。具有功能的类

operator string(); 

定义的可以转换为字符串。

+1

它与铸造无关,它是类型转换,可能由于铸造而发生的事情是另一回事。 – wich 2010-02-10 18:46:21

-2

这似乎是一个十进制数字类型的转换为字符串的运算符。

1

它是一个自动类型转换运算符。你正在谈论的这个类可以隐式转换为一个字符串。这link可能会帮助你几个例子。

+0

链接(http://www.codeguru.com/cpp/tic/tic0131.shtml)不起作用。 – dpatru 2013-02-11 21:32:10