您的位置:首页 > 编程语言 > C语言/C++

C++中修改由const修饰的私有属性

2015-07-18 21:12 471 查看
C++中虽然可以直接修改私有属性的值,但不建议这样操作,此处只是为了告诉大家C++与C语言都是在做内存上面的工作!

代码如下:

#include <iostream>

using std::cout;
using std::endl;

class A
{
private:
    const int test1;
public:

    int test2;
    A():test1(10)
    {
        test2 = 20;
    }
    void print()
    {
        cout << "This is test1 :" << test1 << endl;
        cout << "This is test2 :" << test2 << endl << endl;
    }
};

int
main(int argc, char **argv)
{
    int *test3;
    A t;
    t.print();
    test3 = &t.test2;
    test3--;
    *test3 = 40;
    t.print();
}


测试结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: