强制转换运算符可以是显式的吗? [英] Can a cast operator be explicit?

查看:31
本文介绍了强制转换运算符可以是显式的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当涉及到构造函数时,添加关键字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:

希望有所帮助.

这篇关于强制转换运算符可以是显式的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆