首先,我定义一个整数指针和类A。我想传递一个指向A方法的指针来存储它。

我发现,当我调用A方法时,类A的整数成员总是会变化。

我对如何避免这些更改感到困惑。

#include <IOSTREAM>

using namespace std;

class   A
{
private:
   int* a;
public:
   A()
   {

   };
   ~A()
   {

   };

void setA(int n)
{
    cout << "n == " << n << "&n == " << &n << endl;
    a = &n;
    cout << "now a== " << a << endl;
}

void PassA(int* &outint)
{
    cout << "a == " << a <<  "  *a == " << *a <<endl;
    outint = a;
    cout << "outint = " << outint << endl;
}

void Print()
{
    cout << "a ==================== " << a << endl;
    cout << "*a ==================== " << *a << endl;
}
};

int main()
{
A A_1;
int num = 5;
    A_1.setA(num);

    int *intb= NULL ;
    A_1.PassA(intb);
    //When the line above done,the value of A_1.a will change.
    cout << "intb ==  " << intb << endl;
    cout << "*intb =="  << *intb << endl;
    cout << "num ==" << num << endl;
A_1.Print();
return 0;
}


输出:

n == 5&n == 0x28fe90
现在a == 0x28fe90
a == 0x28fe90 * a == 2686708
outint = 0x28fe90
intb == 0x28fe90
* intb == 4619604
num == 5
一个==================== 0x28fe90
* a ===================== 4619604

最佳答案

您正在将内存位置设置为堆栈上的值。方法结束时,堆栈值将被丢弃。如果必须分配自己的内存,请使用new和delete进行操作:

void setA(int n)
{
    cout << "n == " << n << "&n will be different every time" << endl;
    a = new int();
    *a = n;
    cout << "now a== " << a << endl;
}


另外,如果要在被调用方中使用变量的实际地址,则需要传递一个int指针而不是int:

void setA(int* n)
{
    cout << "n == " << *n << " &n = " << n << endl;
    a = n;
    cout << "now a== " << a << endl;
}

关于c++ - 为什么存储整数的内存块的值反复变化?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18501560/

10-12 16:14