2017-09-11 54 views
3

我正在研究超載問題,而且我完全被升級困惑。我查看了SO(implicit conversion sequence in function overloading)中的一些文章,我確定有更多文章可用,但無法找到正確的文章。我也是指http://www.dcs.bbk.ac.uk/~roger/cpp/week20.htm。 我在看Stroustrup的C++編程特別版,並且遇到了下面的解釋。超載時參數的提升

Finding the right version to call from a set of overloaded functions is done by looking for a best match between the type of the argument expression and the parameters (formal arguments) of the functions. To approximate our notions of what is reasonable, a series of criteria are tried in order: 1 Exact match [2] Match using promotions; [3] Match using standard conversions [4] Match using user-defined conversions [5] Match using the ellipsis ......

void print(int); 
void print(double); 
void print(long); 
void print(char); 
void h(char c, int i, short s, float f) 
{ 
    print(s); // integral promotion: invoke print(int) 
    print(f); // float to double promotion: print(double) 
} 

我寫了下面的代碼。我在想,如果我調用值爲1的函數,func1(long)將被調用,因爲促銷發生。但我得到錯誤消息「錯誤:重載調用'func1(int)'不明確」。它不用甚至無符號的char類型的變量調用該函數。

此外,如果我通過調用func1(3.4f),func1(double)被調用,促銷發生在我的期望。爲什麼1不被提升爲long int,但爲什麼float被提升爲double?什麼樣的整數促銷活動?

void func1(unsigned char speed) 
    { 
     cout<<"Func1 with unsigned char: speed =" << speed <<" RPM\n"; 
    } 

    void func1(long speed) 
    { 
     cout<<"Func1 with long Int: speed =" << speed <<" RPM\n"; 
    } 

    void func1(double speed) 
    { 
     cout<<"Func1 with double: speed =" << speed <<" RPM\n"; 
    } 

    int main(void) 
    { 
     func1(1); 
     func1(3.4f); 
     return(0); 
    } 

回答

1

該標準規定:

[C++11: 4.13/1]: ("Integer conversion rank")

Every integer type has an integer conversion rank defined as follows:

  • [..]
  • The rank of long long int shall be greater than the rank of long int, which shall be greater than the rank of int, which shall be greater than the rank of short int , which shall be greater than the rank of signed char.
  • The rank of any unsigned integer type shall equal the rank of the corresponding signed integer type.
  • [..]

這就要求在你的榜樣歧義。

至於func1(3.4f);,它只是一個從浮子雙重推動下,這是最好的比賽,因爲其他兩個重載方法有longunsigned char

還要檢查這個table

enter image description here

其中一節規定:

[conv.fpprom]: (7.7 Floating-point promotion)

  • A prvalue of type float can be converted to a prvalue of type double . The value is unchanged.
  • This conversion is called floating-point promotion.
+0

感謝@StoryTeller!那麼是的,但不是一個更好的比賽? – gsamaras

+0

@StoryTeller感謝您幫助我改進我的答案。我更新了,現在看起來如何? – gsamaras

+0

這意味着在整數類型的情況下,不會發生促銷,我們需要爲每個整數類型重載函數?另外,如果我有func1(char)和func1(unsigned char),我怎麼能看到func1(unsigned char)函數被調用?可能我需要傳遞一個ASCII值超過127的字符,這在鍵盤上可能是不可能的! – Rajesh