函数重载可能发生在具有相同数量参数的两个成员函数之间,如果其中一个被声明为 const。
但是,如果一个函数有一个 const 参数,而另一个函数有相同类型的非常量参数呢?它适用于引用和指针吗?如果 C++ 提供它,为什么它提供?如果您知道,请与我分享原因。
下面是帮助您理解上述场景的示例。
void fun(const int i)
{
cout << "fun(const int) called ";
}
void fun(int i)
{
cout << "fun(int ) called " ;
}
int main()
{
const int i = 10;
fun(i);
return 0;
}
输出:编译器错误:redefinition of 'void fun(int)'
void fun(char *a)
{
cout<<"non-const fun() called";
}
void fun(const char *a)
{
cout<<"const fun() called";
}
int main()
{
const char *ptr = "GeeksforGeeks";
fun(ptr);
return 0;
}
输出:调用了 const fun()
为什么在 C++ 中允许第二个?