当涉及到构造函数时,添加关键字explicit
可以防止热心的编译器在不是程序员的初衷时创建对象。这种机制也可用于铸造操作员吗?
struct Foo
{
operator std::string() const;
};
例如,在这里,我希望能够Foo
转换为 a std::string
,但我不希望这种转换隐式发生。
当涉及到构造函数时,添加关键字explicit
可以防止热心的编译器在不是程序员的初衷时创建对象。这种机制也可用于铸造操作员吗?
struct Foo
{
operator std::string() const;
};
例如,在这里,我希望能够Foo
转换为 a std::string
,但我不希望这种转换隐式发生。
是和否。
这取决于您使用的 C++ 版本。
explicit
类型转换运算符例子,
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 ,则它被称为“上下文转换运算符”。此外,如果您想了解有关隐式和显式转换的更多信息,请阅读此主题:
希望有帮助。