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:
- 隐式与显式转换
希望有所帮助.
这篇关于强制转换运算符可以是显式的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:强制转换运算符可以是显式的吗?
基础教程推荐
- 初始化列表*参数*评估顺序 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- CString 到 char* 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
