C++编程思想 第1卷 第3章 修改外部对象 按值传递

函数传递参数时,函数内部参数会形成一个拷贝,这称为按值传递


//: C03:PassByValue.cpp
// From Thinking in C++, 2nd Edition
// Available at http://www.BruceEckel.com
// (c) Bruce Eckel 2000
// Copyright notice in Copyright.txt
#include <iostream>
using namespace std;

void f(int a) {
  cout << "a = " << a << endl;
  a = 5;
  cout << "a = " << a << endl;
}

int main() {
  int x = 47;
  cout << "x = " << x << endl;
  f(x);
  cout << "x = " << x << endl;
  getchar();
} ///:~

在f(),a是局部变量,在调用f()期间存在。
a是函数参数,调用时参数传递来初始化a的值。


调用f(),为变量a分配临时空间,拷贝x的值来初始化a。
f()结束后,a就没了
f()内部,x在f()外面,x是外部对象 outside object
局部变量不影响外部变量,他们存储位置不同


输出
x = 47
a = 47
a = 5
x = 47


猜你喜欢

转载自blog.csdn.net/eyetired/article/details/80603583
今日推荐