演员可以明确吗?

qdi*_*dii 83 c++ casting explicit operator-keyword

当涉及构造函数时,添加关键字会explicit阻止热情的编译器在不是程序员的第一个意图时创建对象.这种机制是否也适用于铸造操作员?

struct Foo
{
    operator std::string() const;
};
Run Code Online (Sandbox Code Playgroud)

例如,在这里,我希望能够投入Foo到一个std::string,但我不希望这种投射是隐含的.

Naw*_*waz 100

是和否.

这取决于您使用的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 
}
Run Code Online (Sandbox Code Playgroud)

编译它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 
Run Code Online (Sandbox Code Playgroud)

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

顺便说一下,在C++ 11中,显式转换运算如果转换为布尔值则称为"上下文转换运算符".另外,如果您想了解有关隐式和显式转换的更多信息,请阅读以下主题:

希望有所帮助.

  • 即使在C++ 03中,也很容易避免隐式转换.只需调用函数`toString`,而不是`operator std :: string`.当然,这可能会导致某些模板出现问题.我总是使用`toString`,它从来没有给我带来任何问题,但我想这可能取决于你的编码风格. (9认同)
  • 我改用`to_string`.它有助于它是C++ 11所称的,因此它有助于编写向前兼容的代码_and_它有助于模板. (2认同)
  • @Bin:因为编写`if(std :: cin)`时编译器会*上下文*调用`explicit operator bool()`.请注意,此处发生的转换(非正式地)称为*contextual*conversion,**不是***隐式*转换. (2认同)