2017-09-11 5 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が倍に昇格されるのですか?どの整数型プロモーションが開催されますか?

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へのプロモーションであり、これは他の2つのオーバーロードされたメソッドがlongunsigned charであるため、ベストマッチです。

副次句が指定

enter image description here

はまた、このtableチェック

[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

関連する問題