函数变量作用域
- 内部变量不能被return,编辑器clion 提示
Address of stack memory associated with local variable ‘s’ returned
#include <iostream>
using namespace std;
int *topic(){
int s[3] = {1, 2, 3};
return s;
}
int main(){
int *x;
x = topic();
cout << "x[0] = " << x[0] << endl;
cout << "end" << endl;
}
- 执行后,控制台没有任何打印,连end也没有打印出来, 查看文章后
https://bbs.csdn.net/topics/391881607
- 得出结论在内部定义的数据,是不可以被返回的,而后面的语句既不报错,也不执行。
- 修改后, 可正常执行
#include <iostream>
using namespace std;
int *topic(int s[]){
return s;
}
int main(){
int *x;
int s[3] = {1, 2, 3};
x = topic(s);
cout << "x[0] = " << x[0] << endl;
cout << "end" << endl;
}
函数参数中的 &
- 返回类型 函数名(类名 & a){} 和 返回类型 函数名(类名 a) 之间的区别
- 有 &, 对象在函数中被修改,在函数外的对象也会发生变化
#include <iostream>
using namespace std;
class Man{
public:
int x = 1;
};
void change(Man & a){
a.x = 2;
}
int main(){
Man a;
change(a);
cout << a.x << endl;
return 0;
}
------------- 结果为 2 ---------------------
- 没有 &, 对象在函数中被修改,在函数外的对象不会发生变化
#include <iostream>
using namespace std;
class Man{
public:
int x = 1;
};
void change(Man a){
a.x = 2;
}
int main(){
Man a;
change(a);
cout << a.x << endl;
return 0;
}
------------- 结果为 1 ---------------------
- 究其原因,是因为 带有 & 是将该对象的地址传递进去,也就是a对象是原封不动地传递进去
- 而不带有 & 是将a 对象复制一份,然后在传递进去,本质上,函数内的a对象和函数外的a对象不是同一个对象