但是,类型转换没有任何问题,特别是如果你习惯static_cast这样做的话.这就是你应该使用的.它允许编译器验证类型转换并确保它是安全的.
要更改<<运算符的行为,您必须覆盖值的默认<<运算符char,例如:
std::ostream& operator <<(std::ostream &os, char c)
{
os << static_cast<int>(c);
return os;
}
char c = ...;
std::cout << c;
Run Code Online (Sandbox Code Playgroud)
您可以创建一个自定义类型,该类型接受char输入,然后<<为该类型实现运算符,例如:
struct CharToInt
{
int val;
CharToInt(char c) : val(static_cast<int>(c)) {}
};
std::ostream& operator <<(std::ostream &os, const CharToInt &c)
{
os << c.val;
return os;
}
char c = ...;
std::cout << CharToInt(c);
Run Code Online (Sandbox Code Playgroud)
你可以创建一个类似的函数,然后你不必覆盖<<运算符,例如:
int CharToInt(char c)
{
return c;
}
char c = ...;
std::cout << CharToInt(c);
Run Code Online (Sandbox Code Playgroud)