give me an example to explain 值传递
时间: 2023-07-25 08:46:12 浏览: 48
Sure! Here's an example to explain the concept of "passing by value" in C++:
```
#include <iostream>
using namespace std;
void increment(int x) {
x++; // increment the value of x
cout << "Value of x inside the function: " << x << endl;
}
int main() {
int num = 5;
cout << "Value of num before function call: " << num << endl;
increment(num); // passing num by value to the function
cout << "Value of num after function call: " << num << endl;
return 0;
}
```
In this example, we have defined a function `increment` that takes an integer parameter `x`. Inside the function, we increment the value of `x` by 1 and print its value. In the `main` function, we define an integer variable `num` and initialize it to 5. We then print the value of `num`, call the `increment` function, and print the value of `num` again.
When we pass `num` to the `increment` function, a copy of the value of `num` is created and passed to the function. This means that any changes made to `x` inside the function do not affect the value of `num` outside the function. So, even though we increment the value of `x` inside the function, the value of `num` remains unchanged outside the function.
When we run the above code, the output will be:
```
Value of num before function call: 5
Value of x inside the function: 6
Value of num after function call: 5
```
As you can see, the value of `num` remains unchanged after the function call, even though we incremented the value of `x` inside the function. This is because `num` was passed to the function by value, and any changes made to the value of `x` inside the function do not affect the value of `num` outside the function.