2017-09-11 2 views
3

과부하에 대해 공부하고 있었고 완전히 승진과 혼동을 느낍니다. 나는 SO (implicit conversion sequence in function overloading)에있는 몇몇 기사를 보았고, 더 많은 것이 가능하다고 확신하지만 올바른 기사를 찾지 못했습니다. 나는 또한 http://www.dcs.bbk.ac.uk/~roger/cpp/week20.htm을 언급하고 있었다. 저는 Stroustrup이 C++ Programming 특별판을보고 다음 설명을 보았습니다.과부하 중 매개 변수 승격

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)'호출이 모호합니다." unsigned 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);의 경우 float에서 double까지의 프로모션 일 뿐이며 다른 두 개의 오버로드 된 메소드는 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) 함수가 호출 된 경우 어떻게 볼 수 있습니까? 아마 키보드에서 가능하지 않을 수도있는 127 이상의 ASCII 값을 가진 문자를 전달해야합니다! – Rajesh