我了解什么是函数重载。但是,我很好奇编译器如何区分这些重载函数。假设我有以下两个重载的函数定义。
#include <iostream>
int sum(int a, int b);
int sum(vector<int> a, vector<int> b);
那么,编译器如何确定要调用的函数?我了解逻辑,它根据参数的数据类型进行区分。但是,它是如何实现的?
答案 0 :(得分:1)
您所说的一切都取决于参数类型,可能是通过转换:
#include <iostream>
#include <vector>
using namespace std;
int sum(int, int)
{
cout << "ints" << endl;
}
int sum(vector<int>, vector<int>)
{
cout << "vectors" << endl;
}
class C1 {
public:
operator int() { return 0; }
};
class C2 {
public:
operator int() { return 0; }
operator vector<int>() { vector<int> v ; return v; }
};
int main()
{
sum(1, 2); // ints
sum(1.2, 3); // ints, use conversion from double to int
vector<int> v;
sum(v, v); // vectors
// sum(v, 0); no matching function for call to 'sum(std::vector<int>&, int)'
C1 c1;
sum(c1, c1); // use conversion from C1 to int
C2 c2;
//sum(c2, c2); call of overloaded 'sum(C2&, C2&)' is ambiguous
return 0;
}
编译和执行:
pi@raspberrypi:/tmp $ g++ -pedantic -Wextra c.cc
pi@raspberrypi:/tmp $ ./a.out
ints
ints
vectors
ints