我试图通过指针访问数据成员,因此我编写了以下代码:
#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的值的副本????
*a++;
并不意味着:
a
a
)*a++;
手段:
a
a
使用(*a)++;
以增量是什么指向。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句