【问题标题】:Can a cast operator be explicit?强制转换运算符可以是显式的吗?
【发布时间】:2012-01-04 13:52:03
【问题描述】:

当涉及到构造函数时,添加关键字explicit 可以防止热心的编译器在不是程序员的初衷时创建对象。这种机制也适用于铸造运营商吗?

struct Foo
{
    operator std::string() const;
};

例如,在这里,我希望能够将 Foo 转换为 std::string,但我不希望这种转换隐式发生。

【问题讨论】:

    标签: c++ casting operator-keyword explicit


    【解决方案1】:

    是和否。

    这取决于您使用的 C++ 版本。

    • C++98 和 C++03 不支持explicit 类型转换运算符
    • 但 C++11 可以。

    例子,

    struct A
    {
        //implicit conversion to int
        operator int() { return 100; }
    
        //explicit conversion to std::string
        explicit operator std::string() { return "explicit"; } 
    };
    
    int main() 
    {
       A a;
       int i = a;  //ok - implicit conversion 
       std::string s = a; //error - requires explicit conversion 
    }
    

    g++ -std=c++0x编译,你会得到这个错误:

    prog.cpp:13:20: 错误:请求从“A”转换为非标量类型“std::string”

    在线演示:http://ideone.com/DJut1

    但是一旦你写了:

    std::string s = static_cast<std::string>(a); //ok - explicit conversion 
    

    错误消失:http://ideone.com/LhuFd

    顺便说一句,在 C++11 中,显式转换运算符如果转换为 boolean,则称为 “上下文转换运算符”。此外,如果您想了解有关隐式和显式转换的更多信息,请阅读此主题:

    希望对您有所帮助。

    【讨论】:

    • 即使在 C++03 中,也很容易避免隐式转换。只需调用函数toString,而不是operator std::string。当然,这可能会导致某些模板出现问题。我一直使用toString,它从来没有给我带来任何问题,但我想这可能取决于你的编码风格。
    • @MatthieuM。就像operator std::string():-)。
    • 我改用to_string。它是 C++11 所称的,因此它有助于编写向前兼容的代码并且它有助于使用模板。
    • std::string s(a)std::string s{a} 也应该作为 static_cast&lt;std::string&gt;(a) 工作。
    • @Bin:因为explicit operator bool() 在您编写if(std::cin) 时由编译器上下文 调用。请注意,这里发生的转换(非正式地)称为 contextual 转换,not implicit 转换。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    相关资源
    最近更新 更多