g ++给出错误:类型'char&'的引用的无效初始化来自'unsigned char'类型的表达式 [英] g++ gives error : invalid initialization of reference of type ‘char&’ from expression of type ‘unsigned char’
问题描述
当我尝试编译以下代码
int main()
{
unsigned char uc;
char & rc = uc;
}
g ++会出现以下错误:char&从表达式的'unsigned char'。使用signed char而不是unsigned char时也会发生同样的情况。
但下面的编译很好
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;
}
为什么不能用变量初始化'char&'类型为'unsigned char',但可以用它初始化'const char&'?
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?
推荐答案
是不是可以用'unsigned char'类型的变量初始化'char&',而且可以用它初始化'const char&'?
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?
因为当 unsigned char
转换为 char $ c $时,后者创建一个临时绑定到const引用c>,你不能用非const引用。
char
, signed char
和 unsigned char
类型,如C ++ 11§3.9.1中所述:
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和unsigned char是三种不同类型
Plain char, signed char, and unsigned char are three distinct types
这篇关于g ++给出错误:类型'char&'的引用的无效初始化来自'unsigned char'类型的表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!