C++ 结构体数据成员

5

我正在使用C++和Linux,遇到了以下问题:

struct testing{
uint8_t a;
uint16_t b;
char c;
int8_t d;

};

testing t;

t.a = 1;
t.b = 6;
t.c = 'c';
t.d = 4;
cout << "Value of t.a >>" << t.a << endl;
cout << "Value of t.b >>" << t.b << endl;
cout << "Value of t.c >>" << t.c << endl;
cout << "Value of t.d >>" << t.d << endl;

我的控制台输出是:

Value of t.a >>
Value of t.b >>6
Value of t.c >>c
Value of t.d >>

看起来int8_t和uint8_t类型缺少t.a和t.d。为什么会这样?

谢谢。

3个回答

10
int8_t和uint8_t类型可能被定义为char和unsigned char。流运算符<<将以字符形式输出它们。由于它们分别设置为1和4,这些值是控制字符而不是可打印字符,因此在控制台上无法看到任何内容。尝试将它们设置为65和66('A'和'B'),然后观察发生了什么。
编辑:如果要输出数字值而不是字符,则需要将它们强制转换为适当的类型:
cout << static_cast<unsigned int>(t.a) << endl;

2
...或将它们输出为 << unsigned(t.a) <<<< unsigned(t.b) << - T.E.D.
1
...或将它们输出为 << static_cast<unsigned int>(t.a) << 和 << static_cast<unsigned int>(t.b) << ... ^_^ ... - paercebal

3
这是因为在选择operator<<重载时,这些变量被视为'char'类型。请尝试如下更改:
cout << "Value of t.a >>" << static_cast<int>(t.a) << endl;

2
这个Linux man页面中,int8_t和uint8_t实际上是作为char进行了typedef的:
typedef signed char int8_t
typedef unsigned char uint8_t

字符的值1和4是控制字符,你可以在这里找到相关信息。

这就是为什么你看不到任何输出。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接