提问者:小点点

通过引用传递参数时的C++类型转换


我有一个函数foo,它带有一个通过引用传递的int参数。 我有一个UINT16_T类型的变量。 我使用reinterpret_cast,下面是代码:

#include <iostream>
#include <stdint.h>


void foo(int &bar) {
    std::cout << "bar = " << bar << std::endl;
    bar += 10;
}

int main() {
    uint16_t baz = 100;
    uint16_t qux = 200;
    foo(reinterpret_cast<int &>(baz));
    std::cout << "baz = " << baz << ", qux = " << qux << std::endl;
    foo(reinterpret_cast<int &>(qux));
    std::cout << "baz = " << baz << ", qux = " << qux << std::endl;
    return 0;
}

输出为:

bar = 100
baz = 110, qux = 200
bar = 7209160
baz = 110, qux = 210

我的问题是:

  1. 为什么在第二次调用foo()时,它打印了一个错误的数字,而变量qux最终是正确的?
  2. 调用参数通过引用传递的函数时,类型强制转换的正确方法是什么?

共1个答案

匿名用户

在函数foo中,std::cout将uint16_t视为int,因此它将额外读取两个字节。 十六进制的200(qux)为0xC8。 0x006E00C8为7209160。 你看到十六进制字符串中的0xC8了吗? 0x006E是110,这意味着std::cout在到达uint16_t时也会从堆栈中抓取baz变量,因为它正在寻找一个整数大小的值。

相关问题


MySQL Query : SELECT * FROM v9_ask_question WHERE 1=1 AND question regexp '(引用|传递|参数|c++|类型|转换)' ORDER BY qid DESC LIMIT 20
MySQL Error : Got error 'repetition-operator operand invalid' from regexp
MySQL Errno : 1139
Message : Got error 'repetition-operator operand invalid' from regexp
Need Help?