C++ 强制转换运算符可以是显式的吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8239356/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 18:14:43  来源:igfitidea点击:

Can a cast operator be explicit?

c++castingoperator-keywordexplicit

提问by qdii

When it comes to constructors, adding the keyword explicitprevents an enthusiastic compiler from creating an object when it was not the programmer's first intention. Is such mechanism available for casting operators too?

对于构造函数,添加关键字explicit可以防止热心的编译器在不是程序员的本意时创建对象。这种机制也适用于铸造操作员吗?

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

Here, for instance, I would like to be able to cast Foointo a std::string, but I?don't want such cast to happen implicitly.

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

回答by Nawaz

Yes and No.

是和否。

It depends on which version of C++, you're using.

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

  • C++98 and C++03 do not support explicittype conversion operators
  • But C++11 does.
  • C++98 和 C++03 不支持explicit类型转换运算符
  • 但是 C++11 可以。

Example,

例子,

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 
}

Compile it with g++ -std=c++0x, you will get this error:

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

prog.cpp:13:20: error: conversion from 'A' to non-scalar type 'std::string' requested

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

Online demo : http://ideone.com/DJut1

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

But as soon as you write:

但是一旦你写:

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

The error goes away : http://ideone.com/LhuFd

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

BTW, in C++11, the explicit conversion operator is referred to as "contextual conversion operator"if it converts to boolean. Also, if you want to know more about implicit and explicit conversions, read this topic:

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

Hope that helps.

希望有帮助。