C++定义一个函数,比较两个数的大小,形参分别使用指针和引用
时间: 2023-11-08 13:06:00 浏览: 95
详谈C++引用&和指针在作为形参时的区别
使用指针形参的函数定义如下:
```c++
void compare(int* a, int* b)
{
if (*a > *b)
cout << *a << " is greater than " << *b << endl;
else if (*a < *b)
cout << *b << " is greater than " << *a << endl;
else
cout << *a << " and " << *b << " are equal" << endl;
}
```
使用引用形参的函数定义如下:
```c++
void compare(int& a, int& b)
{
if (a > b)
cout << a << " is greater than " << b << endl;
else if (a < b)
cout << b << " is greater than " << a << endl;
else
cout << a << " and " << b << " are equal" << endl;
}
```
使用指针形参时需要在函数内部使用`*`操作符来获取指针所指向的变量的值;使用引用形参时可以直接使用变量名来获取其值,因为引用是变量的别名。
阅读全文