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;
}
運行結果: