4

次のコードをコンパイルしようとすると

int main()
{
    unsigned char uc;
    char & rc = uc;
}

g++ は次のエラーを返します: タイプ 'unsigned char' の式からのタイプ 'char&' の参照の初期化が無効です。unsigned char の代わりに signed char を使用すると、同じことが起こります。しかし、以下はうまくコンパイルされます

int main()
{
    unsigned char uc;
    const char & rc = uc;
}

「const char &」を初期化できるのに、「unsigned char」型の変数で「char &」を初期化できないのはなぜですか?

4

3 に答える 3

5

「const char &」を初期化できるのに、「unsigned char」型の変数で「char &」を初期化できないのはなぜですか?

unsigned char後者は、が に変換されるときに const 参照にバインドするための一時的な を作成するため、char非 const 参照では実行できないことです。charsigned char、およびunsigned charは、C++11 § 3.9.1 で説明されているように、3 つの異なる型です。

プレーン char、signed char、および unsigned char は 3 つの異なる型です

于 2013-07-03T16:50:56.183 に答える
0

I have faced to this error today, and just would like to share what I have found.

Bjarne Stroustrup in his book "The C++ Programming Language" Third Edition wrote:

§ 5.5 References

Initialization of a reference is trivial when the initializer is an lvalue (an object whose address you can take; see §4.9.6). The initializer for a ‘‘plain’’ T& must be an lvalue of type T.

The initializer for a const T& need not be an lvalue or even of type T In such cases,

[1] first, implicit type conversion to T is applied if necessary (see §C.6)

[2] then, the resulting value is placed in a temporary variable of type T and

[3] finally, this temporary variable is used as the value of the initializer.

于 2015-02-17T08:32:55.863 に答える