c++++ 函数参数传递有三种方式:按值传递副本,按引用传递引用,按指针传递指针。按值传递不影响实际参数,按引用和指针传递则会影响。
C++ 函数参数的传递方式
在 C++ 中,函数参数可以通过引用、指针或值传递。以下是对每种传递方式的介绍和实际示例:
按值传递 (pass-by-value)
传递函数参数的副本。对副本的任何修改都不会影响传递的实际参数。
void swap(int x, int y) {
int temp = x;
x = y;
y = temp;
}
int main() {
int a = 10, b = 20;
std::cout << "Before swap: a = " << a << ", b = " << b << std::endl;
swap(a, b); // a 和 b 的副本被传给 swap
std::cout << "After swap: a = " << a << ", b = " << b << std::endl;
return 0;
}
输出:
Before swap: a = 10, b = 20
After swap: a = 10, b = 20
按引用传递 (pass-by-reference)
传递函数参数的引用。对引用的任何修改都会影响传递的实际参数。
void swap(int &x, int &y) {
int temp = x;
x = y;
y = temp;
}
int main() {
int a = 10, b = 20;
std::cout << "Before swap: a = " << a << ", b = " << b << std::endl;
swap(a, b); // a 和 b 的引用被传给 swap
std::cout << "After swap: a = " << a << ", b = " << b << std::endl;
return 0;
}
输出:
Before swap: a = 10, b = 20
After swap: a = 20, b = 10
按指针传递 (pass-by-pointer)
传递函数参数的指针。对指针所指向内存的任何修改都会影响传递的实际参数。
void swap(int *x, int *y) {
int temp = *x;
*x = *y;
*y = temp;
}
int main() {
int a = 10, b = 20;
std::cout << "Before swap: a = " << a << ", b = " << b << std::endl;
swap(&a, &b); // a 和 b 的指针被传给 swap
std::cout << "After swap: a = " << a << ", b = " << b << std::endl;
return 0;
}
输出:
Before swap: a = 10, b = 20
After swap: a = 20, b = 10
以上就是C++ 函数参数的传递方式的详细内容,更多请关注编程网其它相关文章!