小编use*_*585的帖子

const_cast 不会改变值

之后const_cast,主函数中的值不会改变。但是当调用外部函数时发生变化,仍然在 main 中打印旧值(const int首先初始化的地方)。

int main() {
    const int i = 5;
    int* p = const_cast<int*>(&i);
    *p = 22;
    std::cout<<i;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

输出是5,为什么?观察窗口显示的值i = 22

观察窗口值

那么为什么它会打印 5 呢?如果我调用外部函数,输出会有所不同:

void ChangeValue(const int i) {
    int* p = const_cast<int*>(&i);
    *p = 22;
    std::cout<<i; //Here the value changes to 22
}

int main() {
    const int i = 5;
    ChangeValue(i); //Value changes to 22 in the ChangeValue function
    std::cout<<i // It again prints 5. …
Run Code Online (Sandbox Code Playgroud)

c++

2
推荐指数
1
解决办法
566
查看次数

使用const_cast <>并更改地址处的值不会更改原始变量

#include <iostream>

using namespace std;

int main()
{
    const int kiNum = 100;
    int* ptr = const_cast<int*>(&kiNum);
    *ptr = 200; 
    cout<<"kiNum: "<<kiNum; // The value still prints 100 on the console??
    return 0;
}

output:
kiNum = 100 
Run Code Online (Sandbox Code Playgroud)

在上面的代码片段中,我试图在const_cast之后更改const整数的值,然后更改地址处的值,但控制台仍然打印旧值(我使用的是visual studio 2012)

c++ c++11

1
推荐指数
1
解决办法
167
查看次数

标签 统计

c++ ×2

c++11 ×1