【发布时间】:2016-05-03 20:13:14
【问题描述】:
阅读this后,我尝试使用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;
}
我预计它不会编译,因为构造函数和运算符具有相同的 c-v 资格。但是它编译成功并且static_cast 调用构造函数而不是运算符。为什么?
(使用带有pedantic 和Wall 标志的gcc 4.8.1 编译)
【问题讨论】:
标签: c++ gcc casting static-cast