[英]Why the first programme does not work but second works ? and in second why the output is as it gives?
#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){ ^
#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;
}
产量
const fun()GeeksforGeeks
在你的第一个版本中,存在歧义,因为ptr
类型为const char*
可以转换为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 &'
}
在第一个程序中,使用指向const char
的指针调用fun()
。 有两个候选者(按价值和参考),编制者无法知道选择哪一个。
在第二个程序中,使用const
指向const char
的const
调用fun()
。 然后编译器可以消除引用传递的版本,因为这个重载不能保证通过引用传递的指针将保持不变。
附加说明:如果第二个函数的签名将给出指针void fun(const char * const &a)
保证(aka: void fun(const char * const &a)
),编译器将无法在第一个和第二个案例中选择。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.