问题
最近在使用pugixml,在阅读源码自带的例程时(docs/samples/load_error_handling.cpp),发现有段代码比较迷惑,
这里生成了一个xml_parse_result的对象result,用于接受doc.load_string()的返回值,紧接着就使用if语句去判断这个result,迷惑就出在这里:按照惯性思维,这个if的判断条件肯定是真,因为这是个具体对象。但是代码这样写,肯定是有原因的,于是查阅源码看下xml_parse_result的实现,
// Parsing result
struct PUGIXML_CLASS xml_parse_result
{
// Parsing status (see xml_parse_status)
xml_parse_status status;
// Last parsed offset (in char_t units from start of input data)
ptrdiff_t offset;
// Source document encoding
xml_encoding encoding;
// Default constructor, initializes object to failed state
xml_parse_result();
// Cast to bool operator
operator bool() const;
// Get error description
const char* description() const;
};
发现倒数第二条语句的注释:Cast to bool operator,意思是转换为bool操作符。再看下这个函数的定义,返回的是个bool值,
PUGI__FN xml_parse_result::operator bool() const
{
return status == status_ok;
}
应该就是这里起作用的,当处于if的条件判断中时,对象会转换为bool值。于是查阅了《C++ primer 5th》,发现14.9节 重载、类型转换和运算符讲到了这点,如下,
类型转换运算符(conversion operator)是类的一种特殊成员函数,它负责将一个类类型的值转换成其他类型。类型转换函数的一般形式如下所示:
operator type() const;
其中type表示某种类型。类型转换运算符可以面向任意类型(除了void之外)进行定义,只要该类型能作为函数的返回类型。因此,我们不允许转换成数组或者函数类型,但允许转换成指针(包括数组指针及函数指针)或者引用类型。
一个类型转换函数必须是类的成员函数;它不能声明返回类型,形参列表也必须为空。类型转换函数通常应该是const。
由于之前看书看到操作符重载时只关注了加减乘除,函数调用符等,没有在意这个,所以出现了迷惑,看来还需要加深学习。
举个栗子
这里再举个简单的例子来佐证这一点,
#include <iostream>
using namespace std;
class TestClass
{
public:
TestClass() : status(1) {}
virtual ~TestClass() {}
int status;
// 如果status等于1就返回true,否则返回false
operator bool() const { return status == 1; }
};
int main()
{
TestClass ss;
ss.status = 1;
if (ss) {
cout << "hello1" << endl;
} else {
cout << "hello2" << endl;
}
ss.status = 0;
if (ss) {
cout << "hello1" << endl;
} else {
cout << "hello2" << endl;
}
return 0;
}
输出结果如下,
可以看出,当对象处于if的条件判断语句中时,会自动转变为bool值。在实际使用中还是比较方便的。
关于对象转换为其它类型的更多细节,请阅读《C++ Primer 5th》的14.9节。
如果有写的不对的地方,希望能留言指正,谢谢阅读。