2015-11-07 43 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

相關問題