编译器如何区分过载函数[重复]

问题描述 投票:0回答:1

这个问题在这里已有答案:

我理解重载函数是什么。但是,我很好奇编译器如何区分这些重载函数。比方说,我有以下两个重载函数定义。

#include <iostream>

int sum(int a, int b);
int sum(vector<int> a, vector<int> b);

那么,编译器如何决定调用哪个函数?我理解逻辑,它根据参数的数据类型进行区分。但是,它是如何实施的?

c++ override overloading
1个回答
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
© www.soinside.com 2019 - 2024. All rights reserved.