|
发表于 2022-8-7 18:06:03
|
显示全部楼层
本帖最后由 傻眼貓咪 于 2022-8-7 18:07 编辑
例子 1:
C#include <stdio.h>
void swap(int *A, int *B) // 只能用指针传入值
{
int C = *B;
*B = *A;
*A = C;
}
int main(void) {
int A = 13, B = 5;
swap(&A, &B); // <--------------- 注意这里 ---------------
printf("A: %d\n", A);
printf("B: %d\n", B);
}
C++#include <iostream>
void swap(int &A, int &B) // 函数参数引用 &
{
int C = B;
B = A;
A = C;
}
using std::cout, std::endl;
int main(void) {
int A = 13, B = 5;
swap(A, B); // <--------------- 注意这里 ---------------
cout
<< "A: " << A << endl
<< "B: " << B << endl;
}
例子 2:
C#include <stdio.h>
int main(void) {
int arr[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 3; ++j)
{
printf("%d ", arr[i][j]);
}
}
return 0;
}
C++#include <iostream>
using std::cout, std::endl;
int main(void) {
int arr[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
for (auto& nums : arr) // <--------------- 注意这里,这里的 nums 就是数组引用
{
for (int num : nums) // <--------------- 注意这里 ---------------
{
cout << num << " ";
}
}
cout << endl;
return 0;
}
|
|