1

我对下面问题的结果有疑问。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 &). 为什么会发生这种行为,谁能解释一下?

4

1 回答 1

4

函数重载决策基于哪个函数更好匹配,而不是哪个函数“首先定义”。

您正在传递 a B,因此f(B&)完全匹配的。

f(int)不是因为它需要转换。

您的程序中没有任何内容可以触发所述转换,但如果f(B&)不存在则会尝试。


顺便说一句,你getValue实际上更像printValue. 它目前有一个int返回类型,但实际上并没有返回任何东西,所以你的程序有未定义的行为。您可以通过使其返回来解决此问题void,但您最好return y改为使用它。

于 2019-09-02T11:36:06.567 回答