#include<iostream>
using namespace std;
class A
{
private:
int *a;
public:
A ()
{
cout<<"123"<<endl;
int q = 10;
a = &q;
cout<<*a<<endl;
}
void Show()
{
cout<<*a<<endl;
}
void Set(A m)
{
int w =101;
m.a = &w;
}
};
int main()
{
A m;
m.Show();
return 0;
}
为什么输出的值不一样 两次
------解决方案--------------------
把q改成全局变量再看一下,q是在构造函数中定义的,离开作用域后可能被其他数据覆盖
#include<iostream>
using namespace std;
int q = 10;//全局
class A
{
private:
int *a;
public:
A ()
{
cout<<"123"<<endl;
a = &q;
cout<<*a<<endl;
}
void Show()
{
cout<<*a<<endl;
}
void Set(A m)
{
int w =101;
m.a = &w;
}
};
------解决方案--------------------
q不在show的作用域内,只要把q置于构造函数和show的作用域之外就行,不必是全局变量
#include<iostream>
using namespace std;
class A
{
private:
int *a;
int q = 10;
public:
A()
{
cout << "123" << endl;
a = &q;
cout << *a << endl;
}
void Show()
{
cout << *a << endl;
}
void Set(A m)
{
int w = 101;
m.a = &w;
}
};
int main()
{
A m;
m.Show();
return 0;
}