/* 传递指针参数 */
// 定义时 void func(int* var){}
// 使用时 func(&var);
void swap(int* x, int* y) {
int temp = *x;
*x = *y;
*y = temp;
}
...
int x = 5, y = 10;
swap(&x, &y);
int[]
/* 传递int类型数组参数 */
// 定义时 void func(int* arr){} 或 void func(int arr[]){}
// 使用时 func(arr);
double avg(int *arr, int size) {}
double avg(int arr[], int size) {
int sum = 0;
for (int i = 0; i < size; ++i)
sum += arr[i];
return double(sum) / size;
}
...
int arr[5] = {1000, 2, 3, 17, 50};
avg(arr, 5);
char[]
/* 传递char类型数组参数 */
// 定义时 void func(const char* str){} 或 void func(char str[]){}
// 使用时 func(str);
void copy(const char* str) {}
void copy(char str[]) {
char str1[50];
strcpy(str1, str);
}
...
copy("Hello Word");
使用以下函数定义可能会警告,建议添加 const 修饰符:
void copy(char* str)
[Warning] deprecated conversion from string constant to 'char*' [-Wwrite-strings]
/* 使用引用传参 */
// 定义时 void func(int& var){}
// 使用时 func(var);
void swap(int& x, int& y) {
int temp = x;
x = y;
y = temp;
}
...
int x = 5, y = 10;
swap(x, y);
/* 使用结构体传参 */
// 定义时 void func(struct Books book){}
// 使用时 func(book);
void printBook(struct Books book) {
cout << "Title : " << book.title << endl;
cout << "Author : " << book.author << endl;
cout << "Subject : " << book.subject << endl;
cout << " ID : " << book.id << endl;
}
...
Books book("C++", "Sun", "编程语言", 1);
printBook(book);
/* 返回指针结果 */
// 定义时 int* func(){}
// 使用时 int* res = func();
int* getRandom( ) {
static int r[5];
srand((unsigned)time(NULL));
for (int i = 0; i < 5; ++i)
r[i] = rand();
return r;
}
...
int *rand = getRandom();
一个变量被返回其引用的意思是:返回变量的别名
如当调用函数 setValue() 时,函数返回 var 的别名 ref , 就可以通过别名修改 var 值。
/* 返回全局变量引用结果 */
// 定义时 int& func(){}
// 使用时 int& ref = func();
int var = 5; // 全局变量
int& setValue() {
int& ref = var;
return ref;
}
...
int& ref = setValue(); // 获取全局变量的引用
cout << "改值前: " << var << endl; // 输出 5
ref = 10; // 通过引用修改全局变量
cout << "改值后: " << var << endl; // 输出 10
/* 返回静态变量引用结果 */
// 定义时 int& func(){}
// 使用时 int& ref = func();
int& getStaticRef() {
static int var = 5; // 静态变量
return var;
}
...
int& ref = getStaticRef(); // 获取静态变量的引用
cout << "改值前: " << ref << endl; // 输出 5
ref = 10; // 通过引用修改静态变量
cout << "改值前: " << ref << endl; // 输出 10
/* 返回结构体结果 */
// 定义时 struct Books func(){}
// 使用时 struct Books book = func();
struct Books setBook(string title, string author, string subject, int id) {
struct Books book;
book.title = title;
book.author = author;
book.subject = subject;
book.id = id;
return book;
}
...
Books book = setBook("C++", "Sun", "编程语言", 1);