C++中修改類的私有屬性的方法

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;
}

運行結果:

這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章