读书人

关于类型转换的几行代码 看得不太懂解

发布时间: 2012-09-06 10:37:01 作者: rapoo

关于类型转换的几行代码 看得不太懂
一个解析xml文件的类,里面很多这样的函数定义

C/C++ code
const TiXmlNode* LastChild( const char * value ) const;            /// The last child of this node matching 'value'. Will be null if there are no children.TiXmlNode* LastChild( const char * _value ) {        return const_cast< TiXmlNode* > ((const_cast< const TiXmlNode* >(this))->LastChild( _value ));    }


定义一个const函数 和一个非const函数的意义是什么,在第二个函数中使用const_cast转换的意义又是什么

[解决办法]
const函数函数,不能修改成员,不能调用类的非const成员函数

return const_cast< TiXmlNode* > ((const_cast< const TiXmlNode* >(this))->LastChild( _value ));
第二个const_cast是为了调用const修饰的LastChild()
第一个const_cast是把返回的const TiXmlNode*转成TiXmlNode*

为何定义两个,不清楚,可能是需求如此。

读书人网 >C++

热点推荐