c – 为什么char既没有签名也没有签名,但是wchar_t是?

前端之家收集整理的这篇文章主要介绍了c – 为什么char既没有签名也没有签名,但是wchar_t是?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
以下C程序编译没有错误
void f(char){}
void f(signed char){}
void f(unsigned char){}
int main(){}

同一程序的wchar_t版本不会:

void f(wchar_t){}
void f(signed wchar_t){}
void f(unsigned wchar_t){}
int main(){}

错误:重新定义’void f(wchar_t)’
void f(签名的wchar_t){}

似乎wchar_t是无符号的.
为什么重载不一致?

解决方法

字符都是不同的类型,可以重载

[basic.fundamental] / 1

[…] Plain char,signed char,and unsigned char are three distinct types,
collectively called narrow character types. […]

wchar_t也是一种不同的类型,但它不能使用signed或unsigned进行限定,只能与标准整数类型一起使用.

[dcl.type] / 2

As a general rule,at most one type-specifier is allowed in
the complete decl-specifier-seq of a declaration or in a
type-specifier-seq or trailing-type-specifier-seq. The only exceptions
to this rule are the following:

[…]

signed or unsigned can be combined with char,long,short,or int.

[dcl.type.simple] / 2

[…] Table 9 summarizes the valid combinations of simple-type-specifiers and the types they specify.

wchar_t的签名是实现定义的:

[basic.fundamental] / 5

[…] Type wchar_t shall have the same size,signedness,and alignment requirements (3.11) as one of the other integral types,called its underlying type.

原文链接:https://www.f2er.com/c/119912.html

猜你在找的C&C++相关文章