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 不支持
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: 错误:请求从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
顺便说一句,在 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:
- 隐式与显式转换
希望有所帮助.
这篇关于强制转换运算符可以是显式的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:强制转换运算符可以是显式的吗?
基础教程推荐
- Windows Media Foundation 录制音频 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 从 std::cin 读取密码 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01