PcA*_*cAF 8 c++ gcc casting static-cast
阅读本文后,我尝试进行以下转换static_cast:
class A;
class B {
public:
B(){}
B(const A&) //conversion constructor
{
cout << "called B's conversion constructor" << endl;
}
};
class A {
public:
operator B() const //conversion operator
{
cout << "called A's conversion operator" << endl;
return B();
}
};
int main()
{
A a;
//Original code, This is ambiguous,
//because both operator and constructor have same cv qualification (use -pedantic flag)
B b = a;
//Why isn't this ambiguous, Why is conversion constructor called,
//if both constructor and operator have same c-v qualification
B c = static_cast<B>(a);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我希望它不能编译,因为构造函数和运算符都具有相同的cv限定.然而,它成功编译并static_cast调用构造函数而不是运算符.为什么?
(使用带有pedantic和Wall标志的gcc 4.8.1编译)
C++ 11标准说(强调我的):
5.2.9静态铸造
4否则,表达
e可以显式转换到类型T使用static_cast的形式的static_cast<T>(e),如果声明T t(e);是良好的形成,对于某些发明临时变量t(8.5).这种显式转换的效果与执行声明和初始化,然后使用临时变量作为转换结果相同.e当且仅当初始化将其用作glvalue时,该表达式才用作glvalue.5否则,
static_cast应执行下列转换之一.不得使用a明确执行其他转换static_cast.
这就解释了为什么static_cast在
B c = static_cast<B>(a);
Run Code Online (Sandbox Code Playgroud)
最终调用的构造函数B.
转换运算符仅在T t(e)格式不正确时使用.