void func(int a)
{
cout << "int a" << endl;
}
void func(int* a)
{
cout << "int* a" << endl;
}
void func(int& a)//这个怎么调用?
{
cout << "int& a" << endl;
}
这三个函数重载中void func(int& a)怎么调用呢?
int a = 5;
int& ref = a;
func(10);//cout << "int a" << endl;
func(&a);//cout << "int* a" << endl;
func(ref);// 错误 有多个重载函数 "func_overload::func" 实例与参数列表匹配
func(a);// 错误 有多个重载函数 "func_overload::func" 实例与参数列表匹配
传ref和a都会有二义性。它们都是int类型变量
函数重载中的值传递和引用传递
- 写回答
- 好问题 0 提建议
- 关注问题
- 邀请回答
-
4条回答 默认 最新
檀越@新空间 2024-03-05 05:06关注没个性,不签名! 上午好☀️☀️☀️️
本答案参考ChatGPT-3.5在函数重载中,我们可以通过不同的参数类型来调用不同的函数。在这个例子中,我们定义了三个函数重载:
func(int a)、func(int* a)和func(int& a)。如果我们想调用
func(int& a)函数,就需要传递一个引用类型的参数。下面是调用func(int& a)函数的几种方式:- 使用一个普通的变量作为参数,然后将该变量的引用传递给
func(int& a)函数。
int n = 5; func(n);- 使用一个引用变量作为参数,直接调用
func(int& a)函数。
int n = 5; int& ref = n; func(ref);- 使用一个引用类型的形参,传递一个具有引用类型的实参。
int n = 5; int& ref = n; func(ref);注意:
- 在调用
func(int& a)函数时,实参必须是一个具有引用类型的变量或引用变量。 - 如果尝试传递一个常量或临时变量给
func(int& a)函数,将会导致编译出错。因为引用类型的参数引用的是实参的内存地址,而常量和临时变量没有固定的内存地址。
下面是修改后的代码:
#include <iostream> using namespace std; void func(int a) { cout << "int a" << endl; } void func(int* a) { cout << "int* a" << endl; } void func(int& a) { cout << "int& a" << endl; } int main() { int n = 5; int* ptr = &n; func(n); // 调用 func(int a) func(ptr); // 调用 func(int* a) func(n); // 调用 func(int& a),通过引用传递调用函数 return 0; }解决评论 打赏 举报无用 1- 使用一个普通的变量作为参数,然后将该变量的引用传递给