【发布时间】:2017-03-04 16:37:53
【问题描述】:
我试图通过指针访问一个数据成员,所以我写了这段代码:
#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;
}
我希望数据成员 (a) 的值会变为 13,但它不会发生。然后我打印了*a的值,我就是垃圾。 我想知道为什么数据成员的值没有改变,而 a 指向它的位置?为什么 *a 包含垃圾,甚至没有数据成员 a 的值的副本???
【问题讨论】:
-
Recommended read。他很好地解释了
*a++(以及变体*++a和++*a)的实际作用。