C++ 为什么第一个方案不起作用,但第二个方案起作用?第二,为什么输出是它给出的? 方案1 方案2 #包括 #包括 使用名称空间std; void fun(const char*a)//通过值传递“geeksforgeks”的地址// { cout

C++ 为什么第一个方案不起作用,但第二个方案起作用?第二,为什么输出是它给出的? 方案1 方案2 #包括 #包括 使用名称空间std; void fun(const char*a)//通过值传递“geeksforgeks”的地址// { cout,c++,function,constants,overloading,C++,Function,Constants,Overloading,在第一个版本中,存在歧义,因为ptr类型的const char*可以转换为const char*&。在第二个版本中,没有歧义,因为这次ptr类型为const char*const,不能转换为const char*& 通常,C常量不能强制转换为类型C& void f(int& x) { cout << x; } void main() { int a = 2; f(a); // This is fine int const b = 2; f(b); /

在第一个版本中,存在歧义,因为
ptr
类型的
const char*
可以转换为
const char*&
。在第二个版本中,没有歧义,因为这次
ptr
类型为
const char*const
,不能转换为
const char*&

通常,
C常量
不能强制转换为类型
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 &'
}

void f(int&x){cout在第一个程序中,使用指向
const char
的指针调用
fun()
。有两个候选项可用(通过值和引用),编译器不知道选择哪一个

在第二个程序中,使用指向
const char
const指针调用
fun()
。然后编译器可以消除引用传递的版本,因为此重载不能保证引用传递的指针保持不变


附加说明:如果第二个函数的签名将提供指针常量保证(aka:
void-fun(const-char*const&a)
)编译器将无法选择第一种或第二种情况。

先生,谢谢您的回答,但我怀疑引用变量只能被引用一次。因此,它们就像常量指针一样,是否仍需要编写“const&a”??因为对于指针,我们可以让它们在初始化后指向不同的地址,所以对于它们,我们需要明确地提到const ptr to const char,但引用变量只能引用一个变量。@VinayakSangar是的,这意味着您只能对指针设置一次引用,例如
const char*&p=ptr;
但一旦完成此操作,您将使用引用,就像它是原始变量一样。因此,在我们的示例中,
p=“hello”
具有与
ptr=“hello”
相同的效果,并且
p++
将增加它引用的指针(即指针ptr的内容)。
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){
      ^
#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;
}
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 &'
}