0

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

我发现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
数量 ==5
===================== 0x28fe90
*a ===================== 4619604
4

1 回答 1

1

您正在将内存位置设置为堆栈上的值。当方法结束时,堆栈值将被丢弃。如果您必须分配自己的内存,请使用 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;
}
于 2013-08-29T03:03:38.570 回答