2011-11-23 64 views
77

当涉及到构造函数时,添加关键字explicit可防止热心编译器在不是程序员的第一意图时创建对象。这种机制是否也适用于铸造操作员?演员可以明确吗?

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

这里,比如,我想是能够施展Foostd::string,但我不希望这样的投含蓄发生。

回答

94

是和否

这取决于您正在使用的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: error: conversion from 'A' to non-scalar type 'std::string' requested

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

但只要你写:

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

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

顺便说一句,在C++ 11中,显式转换操作被称为“上下文相关的转换运算符”如果将其转换为布尔。另外,如果你想知道更多关于隐性和显性的转换,阅读本主题:

希望有所帮助。

+1

+1。可以发布一个C++ 11代码的例子吗? – FailedDev

+1

@FailedDev:完成。 :-) – Nawaz

+1

非常感谢! – FailedDev