转换运算符可以是显式的吗? [英] Can a cast operator be explicit?
问题描述
当涉及到构造函数时,添加关键字 explicit
可以防止热情的编译器在不是程序员的第一个意图时创建对象。此类机制是否也可用于投放运算符?
When it comes to constructors, adding the keyword explicit
prevents an enthusiastic compiler from creating an object when it was not the programmer’s first intention. Is such mechanism available for casting operators too?
struct Foo
{
operator std::string() const;
};
例如,我想要能够 Foo
转换为 std :: string
,但我不希望这种转换隐式发生。
Here, for instance, I would like to be able to cast Foo
into a std::string
, but I don’t want such cast to happen implicitly.
推荐答案
是和否。
这取决于您使用的C ++版本。
It depends on which version of C++, you're using.
- C ++ 98和C ++ 03不支持
显式
类型转换操作符 - 但是C ++ 11。
- C++98 and C++03 do not support
explicit
type conversion operators - But C++11 does.
示例,
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 ,你将得到这个错误:
Compile it with g++ -std=c++0x
, you will get this error:
prog.cpp: 20:错误:从'A'转换为非标量类型'std :: string'请求
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
BTW,在C ++ 11中,显式转换如果它转换为 boolean ,则称为上下文转换运算符。此外,如果您想进一步了解隐式和显式转换,请参阅以下主题:
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:
- Implicit VS Explicit Conversion
。
这篇关于转换运算符可以是显式的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!