为什么第一个程序不起作用而第二个程序起作用?在第二个程序中为什么输出是这样的呢?

3

程序 1

#include <iostream>
#include<string>

using namespace std;

void fun(const char *a)// passing address of "GeeksForGeeks" by value //
{
cout << "const fun() " << a;
}

void fun(const char *&a){// passing address of "GeeksForGeeks" by reference         //
cout << "const reference fun()" <<a;
}
int main()
{
const char *  ptr = "GeeksforGeeks";
fun(ptr);
return 0;
}

错误信息

In function 'int main()':
17:8: error: call of overloaded 'fun(const char*&)' is ambiguous
 fun(ptr);
        ^
17:8: note: candidates are:
6:6: note: void fun(const char*)
 void fun(const char *a)
      ^
11:6: note: void fun(const char*&)
 void fun(const char *&a){
      ^

程序2

#include <iostream>
#include<string>

using namespace std;

void fun(const char *a)// passing address of "GeeksForGeeks" by value //
{
cout << "const fun() " << a;
}

void fun(const char *&a){// passing address of "GeeksForGeeks" by reference         //
cout << "const reference fun()" <<a;
}
int main()
{
const char * const ptr = "GeeksforGeeks";
fun(ptr);
return 0;
}

输出

GeeksforGeeks的const fun()

2个回答

2
在您的第一个版本中,存在歧义,因为类型为const char*ptr可以转换为const char*&。在第二个版本中,没有歧义,因为这次ptr的类型为const char* const,不能转换为const char* &
通常情况下,C const不能被转换为C&类型。
void f(int& x) { cout << x; }

void main() {
   int a = 2;
   f(a); // This is fine
   int const b = 2;
   f(b); // Error: 'void f(int &)' : cannot convert argument 1 from 'const int' to 'int &'
}

2
在第一个程序中,您使用指向const char的指针调用fun()。有两个候选项可用(按值和按引用),编译器无法知道选择哪一个。
在第二个程序中,您使用指向const charconst指针调用fun()。然后编译器可以消除通过引用传递的版本,因为这种重载不能保证通过引用传递的指针将保持不变。
附注:如果第二个函数的签名能够提供指针常量保证(即:void fun(const char * const &a)),则编译器在第一种情况和第二种情况下都无法选择。

先生,感谢您的回答,但我有一个疑问,引用变量只能被引用一次。所以它们就像const指针,那么还需要写“const&a”吗?因为对于指针,我们可以在初始化后将它们指向不同的地址,所以对于它们,我们需要明确指出const ptr to const char,但是引用变量只能被引用一次且仅一次。 - Vinayak Sangar
@VinayakSangar 是的,这意味着你只能一次性地将指针设置为引用,例如 const char *&p=ptr;。但是一旦完成了这个步骤,你可以像使用原始变量一样使用引用。因此,在我们的例子中,p="hello"; 的效果与 ptr="hello"; 相同,而 p++ 将会增加它所引用的指针(即指针 ptr 的内容)。 - Christophe

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接