【发布时间】:2020-01-05 10:40:19
【问题描述】:
我对以下问题的结果有疑问。当从 main 调用函数 f 时,调用转到 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 &)。为什么会发生这种行为,谁能解释一下?
【问题讨论】:
-
仅仅因为 f(B) 是完全匹配的。完全匹配总是会击败需要转换的匹配。
-
catch子句按其声明顺序进行搜索。重载的函数不是。
标签: c++ operator-overloading object-composition