为什么显式运算符 std::string 不起作用

why explicit operator std::string does not work

本文关键字:string 不起作用 std 运算符 为什么      更新时间:2023-10-16

我有一个类,它有一个类型std::string的转换运算符标记为显式。这是类

class MyClass {
public:
// methods ...    
    explicit operator std::string() const {
        // convert to string ...
    }
}

问题是当我在 MyClass 类型的变量上使用 static_cast 时,我收到错误"static_cast从'MyClass'到'std::string aka ..."当我为任何自定义类型定义转换运算符时,我似乎遇到了同样的问题。显式修饰符是否仅用于转换为基元类型,或者这是另一个编译器错误。

下面是一个例子

#include <iostream>
#include <string>
class MyClass {
public:
// methods ...    
    explicit operator std::string() const { 
        return "Hello World";
    }
};

int main() 
{
    MyClass obj;
    std::cout << static_cast<std::string>( obj )  << std::endl;
    return 0;
}

输出为

Hello World

通过更新到最新版本的LLVM解决了问题,该版本完全支持所有C++11功能。