为什么不能在类中引用已声明的朋友类的转发? [英] Why can't forward declared friend class be referred in the class?

查看:49
本文介绍了为什么不能在类中引用已声明的朋友类的转发?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码无法编译:

struct X {
  friend class Y;
  Y* ptr;
};

cppreference 将情况描述为

...如果在朋友声明中使用的类的名称是 尚未声明,它是当场提前声明.

... If the name of the class that is used in the friend declaration is not yet declared, it is forward declared on the spot.

如果地点"表示在其中声明了朋友关系,则可以很好地声明成员Y* ptr.为什么不编译?在标准中哪里禁止这样做?

If the "spot" means where the friend relationship is declared, then it should be fine to declare the member Y* ptr. Why doesn't it compile? Where in the standard prohibits this?

推荐答案

这是网站上的错误.它违反了标准,该标准说友谊声明不能替代正向声明:

This is a mistake on the site. It contradicts the standard, which says that friendship declaration is not a substitute for a forward declaration:

7.3.1.2.3在命名空间中首先声明的每个名称都是该命名空间的成员.如果非本地类中的朋友声明首先声明了一个类,函数,类模板或函数模板,则该朋友是最内层的命名空间的成员.朋友声明本身不会使名称对不合格的查询或合格的查询可见.

7.3.1.2.3 Every name first declared in a namespace is a member of that namespace. If a friend declaration in a non-local class first declares a class, function, class template or function template the friend is a member of the innermost enclosing namespace. The friend declaration does not by itself make the name visible to unqualified lookup or qualified lookup.

关于名称不合格或不合格查询不可见的部分,基本上意味着该名称的行为不像正向声明.

The part about the name not being visible to unqualified or qualified lookup essentially means that the name does not behave like a forward declaration.

这篇关于为什么不能在类中引用已声明的朋友类的转发?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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