C++ const常量值的修改

来源:互联网 发布:刀剑逍遥为什么网络 编辑:程序博客网 时间:2024/05/01 16:52
是不是const的常量值一定不可以被修改呢?
  观察以下一段代码:

  通过强制类型转换,将地址赋给变量,再作修改即可以改变const常量值

以下代码中的change()函数为修改常量值的代码,其中 n = (int *)&num 语句意为:把指向常量num的地址,改为指向整型的地址。

#include <iostream>using namespace std;class Student{public:Student(int n,float s):num(n),score(s){}void change  (int *n,float *s,int a,float b) const {n = (int*)&num;s = (float *)&score;*n = a;*s = b;}void display() const{cout<<num<<" "<<score<<endl;}private:int  num ;float score ;};int main(){const Student stud (101,78.5);stud.display();int *m = NULL;float *n = NULL;stud.change(m,n,101,80.5);stud.display();system("pause");return 0;}