在c ++中的歧义功能 [英] ambigious functions in c++

查看:181
本文介绍了在c ++中的歧义功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道为什么这些声明不起作用(不兼容)

  void f // p1 
void f(const int); // p2
void f(int&); // p3
void f(const int&); // p4

如果我理解得很好,编译器不会发现(int& &)
如果我写f(12),它将无法在两个第一个声明之间选择。
我是对吗?



原因是顶层 const 对一个值参数是不可检测的,并且在声明上是无用的。例如,您可以执行以下操作:

  void foo(int x); //声明
// ...
void foo(const int x){
//定义/实现
}

const 这里是一个对调用者不重要的实现细节, 。该副本也是为什么它不能区别于 int 的原因,从呼叫者一侧它们是完全相同的。



注意, const int& r 没有顶层 const ,它是引用一个常量整数的引用(引用始终是常量)。对于指针,如果未声明 const ,可以更改指针,另请参见此问题 const


I would like to know why these declarations won't work(are not compatible)

void f(int); //p1
void f(const int);//p2
void f(int &);//p3
void f(const int &);//p4

If I understood well, the compiler won't find a difference between (int &) and (const int &) and if I write f(12) it won't be able to choose between the two first declarations.. Am I right?

解决方案

p3 and p4 are perfectly unambiguous and distinguishable, p1 and p2 are not. (And of course p1/p2 are distinguishable from p3 and p4.)

The reason is that top-level const on a value parameter is not detectable and infact useless on a declaration. You can for example do the following:

void foo(int x); // declaration
// ...
void foo(const int x){
  // definition/implementation
}

The const here is an implementation detail that's not important for the caller, since you make a copy anyways. That copy is also the reason why it's not distinguishable from just int, from the callers side it's exactly the same.

Note that const int& r does not have a top-level const, it's the reference that refers to a constant integer (references are always constant). For pointers, which may be changed if not declared const, see also this question for where to put const.

这篇关于在c ++中的歧义功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆