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

C++中修改类的私有属性的方法

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

代码如下:

#include <iostream>

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

class A
{
private:
    int test1;
public:
    int test2;
public:
    A()
    {
        test1 = 10;
        test2 = 2;
    }
    void t()
    {
        cout << "This test1 is :" << test1 << endl;
        cout << "This test2 is :" << test2 << endl << endl;
    }
};

int
main(int argc, char **argv)
{
    A t;
    int *a;
    t.t();
    a = & t.test2;
    a --;
    *a = 30;
    t.t();
    cout << "I love this test..." << endl;
}


运行结果:

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