为什么调用了不合适的重载函数

Why is the unsuitable overloaded function is called?

本文关键字:重载 函数 不合适 调用 为什么      更新时间:2023-10-16

为什么下面的代码总是打印"type is double"?(我在StackOverflow中看到过这个代码)

#include <iostream>

void show_type(...) {
    std::cout << "type is not doublen";
}
void show_type(double value) { 
    std::cout << "type is doublen"; 
}
int main() { 
    int x = 10;
    double y = 10.3;
    show_type(x);
    show_type(10);
    show_type(10.3);
    show_type(y);

    return 0;
}

http://en.cppreference.com/w/cpp/language/overload_resolution说:

标准转换序列总是比用户定义的转换序列或省略号转换序列更好。

   void show_type(double value) { 
        std::cout << "type is doublen"; 
    }

如果你在上面评论行,那么输出将是

type is not double
type is not double
type is not double
type is not double

这意味着编译总是更喜欢CCD_ 1而不是CCD_。

在您的情况下,如果您想调用方法void show_type(…),请在调用此方法show_type(firstParameter,secondParameter) 时传递两个或多个参数

#include <iostream>

void show_type(...) {
    std::cout << "type is not doublen";
}
void show_type(double value) { 
    std::cout << "type is doublen"; 
}
int main() { 
    int x = 10;
    double y = 10.3;
    show_type(x);
    show_type(10);
    show_type(10.3);
    show_type(y);
    show_type(4.0,5); //will called this  method show-type(...) 

    return 0;
}

现在以上线路的输出将是

type is  double
type is  double
type is  double
type is  double
type is not double  //notice the output here

有关var args 的更多信息