我试图通过一个指针来访问数据成员,所以我写这样的代码:通过指针更改私人数据成员是不可能的?
#include <iostream>
#include <string>
using namespace std;
class test{
public:
int * returnAdd();
int getA();
void setmember(int x);
private:
int a;
};
int *test::returnAdd()
{
return &a;
}
int test::getA()
{
return a;
}
void test::setmember(int x)
{
a = x;
return;
}
int main(void)
{
test test1;
int *a = test1.returnAdd();
test1.setmember(12);
*a++;
cout << test1.getA() << endl;
cout << *a << endl;
return 0;
}
我想到的是数据成员的值(一)将成为13,但它不会发生。然后我打印了* a的值,而且我是垃圾。 我不知道为什么数据成员的价值没有改变,而一个指向它的位置?为什么* a包含垃圾,甚至没有数据成员a的值的副本?
[推荐读](http://stackoverflow.com/a/18484907/7571258)。他很好地解释了'* a ++'(以及变体'* ++ a'和'++ * a')的表达实际上所做的。 – zett42