Zha*_*ang 129 c++ char unary-operator
我在cppreference的文档中看到了这个例子std::numeric_limits
#include <limits>
#include <iostream>
int main()
{
std::cout << "type\tlowest()\tmin()\t\tmax()\n\n";
std::cout << "uchar\t"
<< +std::numeric_limits<unsigned char>::lowest() << '\t' << '\t'
<< +std::numeric_limits<unsigned char>::min() << '\t' << '\t'
<< +std::numeric_limits<unsigned char>::max() << '\n';
std::cout << "int\t"
<< std::numeric_limits<int>::lowest() << '\t'
<< std::numeric_limits<int>::min() << '\t'
<< std::numeric_limits<int>::max() << '\n';
std::cout << "float\t"
<< std::numeric_limits<float>::lowest() << '\t'
<< std::numeric_limits<float>::min() << '\t'
<< std::numeric_limits<float>::max() << '\n';
std::cout << "double\t"
<< std::numeric_limits<double>::lowest() << '\t'
<< std::numeric_limits<double>::min() << '\t'
<< std::numeric_limits<double>::max() << '\n';
}
Run Code Online (Sandbox Code Playgroud)
我不明白"+"运算符
<< +std::numeric_limits<unsigned char>::lowest()
Run Code Online (Sandbox Code Playgroud)
我测试了它,用" - "替换它,这也有效.这种"+"运算符有什么用?
Sto*_*ica 37
+
有没有把它unsigned char
变成一个int
.该+
运营商是保值的,但它有它的操作诱导积分促销的效果.这是为了确保您看到一个数值而不是一个(半)随机字符,operator <<
当给定一个字符类型时,它会打印出来.
phu*_*clv 12
没有+
结果会有所不同.以下代码段输出a 97
而不是a a
char ch = 'a';
std::cout << ch << ' ' << +ch << '\n';
Run Code Online (Sandbox Code Playgroud)
原因是因为不同的重载会打印不同类型的数据.没有basic_ostream& operator<<( char value );
超载,std::basic_ostream
并在页面末尾进行了解释
字符和字符串参数(例如,类型
char
或字符串const char*
)由非成员重载处理operator<<
.尝试使用成员函数调用语法(例如,std::cout.operator<<('c');
)输出字符将调用重载之一(2-4)并输出数值.尝试使用成员函数调用语法输出字符串将调用overload(7)并打印指针值.
传递变量时将调用的非成员重载char
是
template< class CharT, class Traits> basic_ostream<CharT,Traits>& operator<<(
basic_ostream<CharT,Traits>& os, char ch );
Run Code Online (Sandbox Code Playgroud)
它在代码点打印出字符 ch
所以基本上如果你传递char
,signed char
或unsigned char
直接到流,它将打印出角色.如果您尝试删除+
上面的行,您会看到它打印出一些"奇怪"或不可见的字符,这不是人们所期望的
如果你希望自己的数值,而不是必须调用过载short
,int
,long
或long long
.要做到这一点最简单的方法是从推进char
到int
与一元加+
.这是一元加运算符的罕见有用应用之一.明确的演员也将有效int
有很多人在SO上面对这个问题
归档时间: |
|
查看次数: |
4070 次 |
最近记录: |