在这里阅读关于转换运算符和构造函数的一些问题让我思考它们之间的相互作用,即当存在"模糊"调用时.请考虑以下代码:
class A;
class B {
public:
B(){}
B(const A&) //conversion constructor
{
cout << "called B's conversion constructor" << endl;
}
};
class A {
public:
operator B() //conversion operator
{
cout << "called A's conversion operator" << endl;
return B();
}
};
int main()
{
B b = A(); //what should be called here? apparently, A::operator B()
return 0;
}
Run Code Online (Sandbox Code Playgroud)
上面的代码显示"被称为A的转换运算符",这意味着调用转换运算符而不是构造函数.如果operator B()
从中删除/注释掉代码A
,编译器将很乐意切换到使用构造函数(不对代码进行其他更改).
我的问题是:
B b = A();
是一个模糊的调用,因此这里必须有某种类型的优先级.这个优先权究竟在哪里确定?(将赞赏C++标准的参考/引用)A
对象应该如何成为一个B
对象, …c++ constructor operators type-conversion conversion-operator
阅读本文后,我尝试进行以下转换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 …
Run Code Online (Sandbox Code Playgroud)