重载解析如何在private修饰符的上下文中起作用? [英] How does overload resolution work in the context of private modifier?

查看:79
本文介绍了重载解析如何在private修饰符的上下文中起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法理解以下C ++代码段的输出.

I am unable to understand the output of the following C++ snippet.

不应objc.fn()调用Afn(),因为B的fn()private,并且在C中不可见.但是,答案是:对fn()的调用是模棱两可的.怎么样?

Should not objc.fn() call A's fn() since B's fn() is private and should not be visible in C. However, the answer is: the call to fn() is ambiguous. How?

#include<iostream>
using namespace std;

class A{
  public:
   void fn() { cout << "1"; }
};
class B{
   void fn() { cout << "2"; }
};
class C: public A, public B {};

int main(){
  C objc;
  objc.fn();
  return 0;
}

推荐答案

根据这本书 C ++模板:完整指南附录B.1,

According to the book C++ Templates: The Complete Guide Appendix B.1,

在非常高的层次上,可以在以下位置处理对命名函数的调用 通过以下方式:

At a very high level, a call to a named function can be processed in the following way:

  1. 会查询名称以形成初始过载集.

  1. The name is looked up to form an initial overload set.

如有必要,可以通过各种方式(例如, 模板推演发生.)

If necessary, this set is tweaked in various ways (for example, template deduction occurs).

与通话完全不匹配的任何候选项(即使在之后 考虑隐式转换和默认参数)是 从过载设置中消除.这导致了一组所谓的 可行的功能候选人.

Any candidate that doesn't match the call at all (even after considering implicit conversions and default arguments) is eliminated from the overload set. This results in a set of so-called viable function candidates.

执行重载解析以找到最佳候选者.如果有 是一个,它被选中;否则,通话不明确.

Overload resolution is performed to find a best candidate. If there is one, it is selected; otherwise, the call is ambiguous.

已检查选定的候选者.例如,如果它是一个 无法访问的私人成员,将发出诊断.

The selected candidate is checked. For example, if it is an inaccessible private member, a diagnostic is issued.

您可以看到,最后检查了访问权限,因此将首先在步骤#4中报告the call to fn() is ambiguous.

As you can see, the access authority is checked at last, so the call to fn() is ambiguous will be reported firstly at step #4.

这篇关于重载解析如何在private修饰符的上下文中起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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