在C++中,方法参数的传递有两种主要方式:值传递(pass-by-value)和引用传递(pass-by-reference)。这两种方式的主要区别在于参数在方法中被复制还是被直接使用。
示例:
#include <iostream>
using namespace std;
void addOne(int x) {
x = x + 1;
cout << "Inside function: "<< x << endl;
}
int main() {
int num = 5;
cout << "Before function call: " << num << endl;
addOne(num);
cout << "After function call: " << num << endl;
return 0;
}
输出:
Before function call: 5
Inside function: 6
After function call: 5
示例:
#include <iostream>
using namespace std;
void addOne(int &x) {
x = x + 1;
cout << "Inside function: "<< x << endl;
}
int main() {
int num = 5;
cout << "Before function call: " << num << endl;
addOne(num);
cout << "After function call: " << num << endl;
return 0;
}
输出:
Before function call: 5
Inside function: 6
After function call: 6
此外,还有一种特殊的引用传递方式,即常量引用(pass-by-const reference),用于传递不应被修改的数据。
示例:
#include <iostream>
using namespace std;
void printNum(const int &x) {
cout << "Inside function: "<< x << endl;
}
int main() {
int num = 5;
cout << "Before function call: " << num << endl;
printNum(num);
cout << "After function call: " << num << endl;
return 0;
}
输出:
Before function call: 5
Inside function: 5
After function call: 5