赞
踩
值传递(Pass by Value):
引用传递(Pass by Reference):
地址传递(Pass by Address):
- #include <iostream>
-
- void changeValue(int x) {
- x = 10;
- }
-
- int main() {
- int num = 5;
- changeValue(num);
- std::cout << "Original value: " << num << std::endl; // 输出结果为 5,因为形参的修改不会影响实参
- return 0;
- }
引用传递示例: - #include <iostream>
-
- void changeValue(int &x) {
- x = 10;
- }
-
- int main() {
- int num = 5;
- changeValue(num);
- std::cout << "Modified value: " << num << std::endl; // 输出结果为 10,因为形参的修改会影响实参
- return 0;
- }
地址传递示例: - #include <iostream>
-
- void changeValue(int *x) {
- *x = 10;
- }
-
- int main() {
- int num = 5;
- changeValue(&num);
- std::cout << "Modified value: " << num << std::endl; // 输出结果为 10,因为通过指针修改了实参的值
- return 0;
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。