2015-11-07 45 views
4

为什么下面的代码总是输出“type is double”? (我看到的StackOverflow此代码)为什么调用不适合的重载函数?

#include <iostream> 


void show_type(...) { 
    std::cout << "type is not double\n"; 
} 

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

int main() { 
    int x = 10; 
    double y = 10.3; 

    show_type(x); 
    show_type(10); 
    show_type(10.3); 
    show_type(y); 


    return 0; 
} 

回答

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

如果u上面一行注释,然后输出将是

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

这意味着编译总是喜欢void show_type(double value)void show_type(...)

你的情况

,如果你想调用的方法无效show_type(...)可以在两个或多个参数当u调用此方法show_type(firstParameter,secondParameter)

#include <iostream> 


void show_type(...) { 
    std::cout << "type is not double\n"; 
} 

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

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 

more info on var-args

相关问题