为什么在以下源代码中不对用户定义的类型执行隐式类型转换?
在注释行上应进行到类型A的隐式类型转换,但没有发生,并且在该行上发生错误。
我想知道此错误的语法规则和解决方案。
#include <iostream>
using namespace std;
class A {
int v;
public:
A(int _v): v(_v) {}
operator int (void) const {
return v;
}
friend ostream& operator << (ostream& os, const A& s) {
return os << "A: " << s.v;
}
};
class B {
int x, y;
public:
B(int _x, int _y): x(_x), y(_y) {}
operator A(void) const {
return A(x+y);
}
};
int main(void)
{
B b(1,2);
cout << A(b) << endl;
cout << (A)b << endl;
cout << b << endl; // error --> why?
return 0;
}
这必须与奥秘规则有关,这些规则与重载分辨率,好友函数,和隐式转换之间的关系有关。因为这不仅涉及隐式转换,所以在这里。您还定义了一个重载operator<<
,它是一个朋友函数。
通过简单地摆脱好友功能,以下代码在gcc 9.2上可以正常编译。对get rid of using namespace std;
, as well也无害:
using namespace std;