C/C++ 更改 const 的值 [英] C/C++ changing the value of a const

查看:21
本文介绍了C/C++ 更改 const 的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一篇文章,但我把它弄丢了.它展示并描述了一些人们应该小心的 C/C++ 技巧.其中一个对我很感兴趣,但现在我正在尝试复制它,我无法将它编译.<​​/p>

这个概念是可以在 C/C++ 中意外更改 const 的值

原来是这样的:

const int a = 3;//我保证我不会改变常量 int *ptr_to_a = &a;//我仍然保证我不会改变诠释*ptr;ptr = ptr_to_a;(*ptr) = 5;//我是个骗子;a 现在是 5

我想把这个给朋友看,但现在我错过了一步.有谁知道开始编译和工作缺少什么?

ATM 我得到从 'const int*' 到 'int*' 的无效转换,但是当我阅读这篇文章时,我尝试过,效果很好.

解决方案

你需要抛弃 constness:

linux ~ $ cat constTest.c#include <stdio.h>无效 modA(int *x){*x = 7;}诠释主要(无效){常量 int a = 3;//我保证我不会改变诠释*ptr;ptr = (int*)( &a );printf("A=%d
", a);*ptr = 5;//我是个骗子,a 现在是 5printf("A=%d
", a);*((int*)(&a)) = 6;printf("A=%d
", a);modA( (int*)( &a ));printf("A=%d
", a);返回0;}linux ~ $ gcc constTest.c -o constTestlinux ~ $ ./constTestA=3A=5A=6A=7linux ~ $ g++ constTest.c -o constTestlinux ~ $ ./constTestA=3A=3A=3A=3

通用答案在 g++ 4.1.2 中也不起作用

linux ~ $ cat constTest2.cpp#include <iostream>使用命名空间标准;诠释主要(无效){常量 int a = 3;//我保证我不会改变诠释*ptr;ptr = const_cast<int*>( &a );cout < 解决方案 

you need to cast away the constness:

linux ~ $ cat constTest.c
#include <stdio.h>


void modA( int *x )
{
        *x = 7;
}


int main( void )
{

        const int a = 3; // I promisse i won't change a
        int *ptr;
        ptr = (int*)( &a );

        printf( "A=%d
", a );
        *ptr = 5; // I'm a liar, a is now 5
        printf( "A=%d
", a );

        *((int*)(&a)) = 6;
        printf( "A=%d
", a );

        modA( (int*)( &a ));
        printf( "A=%d
", a );

        return 0;
}
linux ~ $ gcc constTest.c -o constTest
linux ~ $ ./constTest
A=3
A=5
A=6
A=7
linux ~ $ g++ constTest.c -o constTest
linux ~ $ ./constTest
A=3
A=3
A=3
A=3

also the common answer doesn't work in g++ 4.1.2

linux ~ $ cat constTest2.cpp
#include <iostream>
using namespace std;
int main( void )
{
        const int a = 3; // I promisse i won't change a
        int *ptr;
        ptr = const_cast<int*>( &a );

        cout << "A=" << a << endl;
        *ptr = 5; // I'm a liar, a is now 5
        cout << "A=" << a << endl;

        return 0;
}
linux ~ $ g++ constTest2.cpp -o constTest2
linux ~ $ ./constTest2
A=3
A=3
linux ~ $

btw.. this is never recommended... I found that g++ doesn't allow this to happen.. so that may be the issue you are experiencing.

这篇关于C/C++ 更改 const 的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆