【发布时间】:2017-04-26 04:59:57
【问题描述】:
void func(int x) {
x = 2;
}
int main()
{
int x = 3;
func(x);
cout << "x = " << x << endl;
return 0;
}
我预计输出为 2。为什么没有发生这种情况?一个简单的解释,因为我才刚刚开始学习 c++。然后你能解释一下为什么下面的结果是 5:
void func(int x)
{
x = 2;
}
void function(int *x)
{
*x = 5;
}
int main()
{
int x = 3;
func(x);
function(&x);
cout << "x = "<< x << endl;
return 0;
}
【问题讨论】:
-
另请参阅stackoverflow.com/questions/11736306/…、stackoverflow.com/questions/21215409/…,以及有关 C++ 函数的基本教程:cplusplus.com/doc/tutorial/functions,以及您的指针示例:cslibrary.stanford.edu/104(C++ 版本)。