【问题标题】:Why am i getting 2 as an output?为什么我得到 2 作为输出?
【发布时间】:2018-06-06 04:41:17
【问题描述】:
#include<iostream>
using namespace std;
template<class T>
void f(T &i)
{
    cout<<"1";
}
void f(const int&i)
{
    cout<<"2";
}
int main()
{
    f(7);
}

我使用了模板函数和普通函数。但是带有 const int 参数的函数在调用时正在执行。为什么会这样?

【问题讨论】:

标签: c++


【解决方案1】:

编译代码时,根据参数类型和参数数量,编译器会找到最相关的函数来响应您的函数调用f(7),然后再转到Template 函数。在这种情况下,最相关的函数是void f(const int&amp;i),所以你得到了 2 作为输出。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-22
    • 1970-01-01
    • 1970-01-01
    • 2012-04-26
    • 1970-01-01
    • 2016-03-03
    相关资源
    最近更新 更多