加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 朋友的功能

发布时间:2020-12-16 06:55:19 所属栏目:百科 来源:网络整理
导读:以下是什么意思(特别是突出显示的部分)?为什么表达式’f(a)’被视为’演员表达’? C++03 $3.4./3- “The lookup for an unqualified name used as the postfix-expression of a function call is described in 3.4.2. [Note: for purposes of determining
以下是什么意思(特别是突出显示的部分)?为什么表达式’f(a)’被视为’演员表达’?

C++03 $3.4./3- “The lookup for an unqualified name
used as the postfix-expression of a
function call is described in 3.4.2.
[Note: for purposes of determining
(during parsing) whether an expression
is a postfix-expression for a function
call,the usual name lookup rules
apply. The rules in 3.4.2 have no
effect on the syntactic interpretation
of an expression. For example,

typedef int f;
struct A {
friend void f(A &);
operator int();
void g(A a) {
f(a);
}
};

表达式f(a)是等效于int(a)的强制转换表达式.因为表达式不是函数调用,所以参数依赖的名称查找(3.4.2)不适用,并且找不到友元函数f. ]”

有什么想法吗?

解决方法

这意味着解析器首先确定括号前面的表达式是id还是后缀表达式.在这种情况下,它看到f,并且最接近的f定义为typedef int f – 因此它总结表达式被解释为int(a)并且不执行Koenig查找.

我们有这个代码(你在网上尝试一下:http://ideone.com/clone/eRKvP)

typedef int f;
namespace x {
  struct A {
    friend void f(A &);
    //friend void f(); // # 1
    operator int();
    void g(A a) {
      //void f();  // # 2
      (void)f(a); // # 3
    }
  };
}

如果你从g声明了一个(无关的)函数f,它将被解释为函数调用,并且Koenig查找将找到正确的重载(参见第2行).

f的朋友声明不应该适用于此,因为

11.4/1: … The name of a friend is not in the scope of the class,

然而,让我感到不安的是,取消注释#1会使编译器(在本例中为gcc)也调用x :: f(A&).不知道为什么会这样. [在Comeau Online编译器中,它按预期工作(例如,#1不影响第3行).但是,最新的测试版在编译此代码时遇到了问题.

PS:正如litb所说,C 0x中的规则有点不同:

3.4.2/3:

Let X be the lookup set produced by
unquali?ed lookup (3.4.1) and let Y be
the lookup set produced by argument
dependent lookup (de?ned as follows).
If X contains

  • a declaration of a class member,or
  • a block-scope function declaration that is not a using-declaration,or
  • a declaration that is neither a function or a function template

then Y is empty. Otherwise Y is the
set of declarations found in the
namespaces associated with the

粗体项将使编译器仅考虑void f()并且对于太多参数而失败.

它似乎是由issue 218号决议引入的.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读