char的类型有几种呢?无非是unsigned char 和signed char,是吧。让我们用下面的程序来做个测试
template
<
typename T
>
struct Type
{
inline static void print()
{
std::cout << " Unknow " << std::endl;
}
};
template <>
struct Type < signed char >
{
inline static void print()
{
std::cout << " signed char " << std::endl;
}
};
template <>
struct Type < unsigned char >
{
inline static void print()
{
std::cout << " unsigned char " << std::endl;
}
};
int main()
{
Type < unsigned char > ::print();
Type < signed char > ::print();
Type < char > ::print();
return 0 ;
}
struct Type
{
inline static void print()
{
std::cout << " Unknow " << std::endl;
}
};
template <>
struct Type < signed char >
{
inline static void print()
{
std::cout << " signed char " << std::endl;
}
};
template <>
struct Type < unsigned char >
{
inline static void print()
{
std::cout << " unsigned char " << std::endl;
}
};
int main()
{
Type < unsigned char > ::print();
Type < signed char > ::print();
Type < char > ::print();
return 0 ;
}
输出内容:
unsigned char
signed char
Unknow
结果出乎意料,输出内容说明编译器把unsigned char、signed char和char识别成三种不同的类型。
那么char类型是有符号还是无符号呢?通过下面的程序来求证一下(以下程序在Microsoft visual C++ 2003、windows 2003下编译并运行)。
int
main()
{
char c = - 1 ;
int i = c;
std::cout << i << std::endl;
return 0 ;
}
{
char c = - 1 ;
int i = c;
std::cout << i << std::endl;
return 0 ;
}
输出内容:
-1
输出内容证明char是有符号的,但这并不可靠,各家的编译器不保证char都是signed或unsigned。可以用IDE修改char有符号还是无符号,在Microsoft visual C++ 2003中, 通过“项目->属性->C/C++->语言->默认char无符号”进行修改
总结:
C++中char、unsigned char和signed char是三种类型,因此在函数重载和模板偏特化时,应注意重写它们的三个版本。虽然它们是三种类型,但char不是unsigned char就是signed char,且char是否有符号可由编译器改变。因此不因编写依赖char是有符号还是无符号的代码。