我对下面问题的结果有疑问。f从 main调用函数时,f(B &)尽管我重载了 int 运算符并且f(int)首先定义了,但调用会转到。
如果我注释掉该f(B &)函数,则调用将转到f(int)并打印 5。
#include <iostream>
using namespace std;
class A{
int y;
public:
A(int y=2):y(y){}
int getValue(){
cout<<y<<endl;
}
};
class B{
int x;
public:
A a;
B(int x=5):x(x){}
operator int(){
return x;
}
};
void f(int x){
cout<<x<<endl;
}
void f(B &b){
b.a.getValue();
}
int main() {
B b;
f(b);
}
我期待它能够f(int)发挥作用,print 5但它却相反prints 2。为什么它不去f(int)而不是f(B &). 为什么会发生这种行为,谁能解释一下?