强制转换运算符可以是显式的吗?

在构造函数方面,添加关键字 explicit可以防止热心的编译器在不是程序员的初衷的情况下创建对象。这种机制是否也适用于铸造操作员?

struct Foo
{
operator std::string() const;
};

例如,在这里,我希望能够将 Foo强制转换为 std::string,但是我不希望这样的强制转换隐式地发生。

26547 次浏览

Yes and No.

It depends on which version of C++, you're using.

  • C++98 and C++03 do not support explicit type conversion operators
  • But C++11 does.

Example,

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
}

Compile it with g++ -std=c++0x, you will get this error:

prog.cpp:13:20: error: conversion from 'A' to non-scalar type 'std::string' requested

Online demo : http://ideone.com/DJut1

But as soon as you write:

std::string s = static_cast<std::string>(a); //ok - explicit conversion

The error goes away : http://ideone.com/LhuFd

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:

Hope that helps.