美文网首页
C++类型转换函数

C++类型转换函数

作者: NullUser | 来源:发表于2023-01-10 14:44 被阅读0次

基本

C++提供类型转换函数,将当前类转换为其他类型。
类型转换函数的语法格式为:

operator type()
{
  return data;
}

其中,operator为关键字,type为要转换的类型,data为返回值,返回值类型应该为type。

示例

参考GDAL源码CPLString类的实现:

class CPLSTRING_CLASS_DLL CPLString : public std::string
{
public:
    /** Return string as zero terminated character array */
    operator const char* (void) const { return c_str(); }
};

在CPLString的类型转换函数中,将CPLString类转换为const char *类型。
在使用CPLString时即可实现如下操作:

CPLString str;
const char *pStr = str; //如果没有实现类型转换函数,此处会报错

相关文章

网友评论

      本文标题:C++类型转换函数

      本文链接:https://www.haomeiwen.com/subject/fndvcdtx.html