为什么我不能在 C++ 中使用指针更改常量的值?

问题描述 投票:0回答:1

我正在编写代码示例,演示如何使用 C++ 中的指针“搬起石头砸自己的脚”。

创建崩溃的代码很容易。但现在我正在尝试编写可以更改常量值的代码,但它不起作用。这是示例代码:

int main()
{
    int first = 1;
    int second = 2;
    const int the_answer = 42;
    int third = 3;
    int fourth = 4;

    cout << "First  : " << &first << " -> " << first << endl;
    cout << "Second : " << &second << " -> " << second << endl;
    cout << "TheAns : " << &the_answer << " -> " << the_answer << endl;
    cout << "Third  : " << &third << " -> " << third << endl;
    cout << "Fourth : " << &fourth << " -> " << fourth << endl << endl;

    for (int *pc = &second; pc < &third; pc++) {
        *pc = 33;
        cout << pc << "->" << * pc << endl;
    }

    cout << "First  : " << &first << " -> " << first << endl;
    cout << "Second : " << &second << " -> " << second << endl;
    cout << "TheAns : " << &the_answer << " -> " << the_answer << endl;
    cout << "Third  : " << &third << " -> " << third << endl;
    cout << "Fourth : " << &fourth << " -> " << fourth << endl << endl;

    return 0;
}

我可以在输出中看到常量(0x56F40FF574)的地址内容被覆盖:

First  : 00000056F40FF534 -> 1
Second : 00000056F40FF554 -> 2
TheAns : 00000056F40FF574 -> 42
Third  : 00000056F40FF594 -> 3
Fourth : 00000056F40FF5B4 -> 4

00000056F40FF554->33
00000056F40FF558->33
00000056F40FF55C->33
00000056F40FF560->33
00000056F40FF564->33
00000056F40FF568->33
00000056F40FF56C->33
00000056F40FF570->33
00000056F40FF574->33       <---
00000056F40FF578->33
00000056F40FF57C->33
00000056F40FF580->33
00000056F40FF584->33
00000056F40FF588->33
00000056F40FF58C->33
00000056F40FF590->33
First  : 00000056F40FF534 -> 1
Second : 00000056F40FF554 -> 33
TheAns : 00000056F40FF574 -> 42
Third  : 00000056F40FF594 -> 3
Fourth : 00000056F40FF5B4 -> 4

我用调试器单步调试代码,我看到常量 the_answer 的值在“locals”窗口中发生了变化。但随后,cout显示原始值。

c++ pointers constants memory-address pointer-arithmetic
1个回答
0
投票

在 C++ 中,您无法通过指针或任何方法更改常量变量的值,因为

const
限定符强制执行不变性,从而防止对变量值进行任何修改。

© www.soinside.com 2019 - 2024. All rights reserved.