g++ gives error : invalid initialization of reference of type ‘char&’ from expression of type ‘unsigned char’

假如想象 提交于 2019-12-23 12:50:02

问题


when I try to compile the following code

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

g++ gives the following error : invalid initialization of reference of type ‘char&’ from expression of type ‘unsigned char’. The same happens when using signed char instead of unsigned char. But the following compiles well

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

Why isn't it possible to initialize 'char &' with a variable of type 'unsigned char' while it is possible to initialize 'const char &' with it?


回答1:


Why isn't it possible to initialize 'char &' with a variable of type 'unsigned char' while it is possible to initialize 'const char &' with it?

Because the latter creates a temporary to bind to the const reference when the unsigned char is converted to a char, something you can't do with non-const references. char, signed char, and unsigned char are three distinct types, as explained in C++11 § 3.9.1:

Plain char, signed char, and unsigned char are three distinct types




回答2:


"The C++ compiler treats variables of type char, signed char, and unsigned char as having different types."

The following link will clarify: http://msdn.microsoft.com/en-us/library/cc953fe1.aspx

change the following:

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



回答3:


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.



来源:https://stackoverflow.com/questions/17453738/g-gives-error-invalid-initialization-of-reference-of-type-char-from-expre

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!