7

我的理解是,friend如果使用说明符,则声明也可以用作类的前向声明class,如下例所示:

class A
{
    friend class B;
    B* b;
};

class B {};

int main() {}

但是,g++(4.6.3 和 4.7.0)给了我以下错误(g++-4.7 应该支持扩展的朋友声明),这是没有前向声明的预期:

main.cpp:6:2:错误:“B”没有命名类型

为了确认我对friend class B;应该作为前向声明的期望,我找到了这个答案这个答案,但都不是决定性的(或者我至少不能从他们那里得出很多结论)所以我试图咨询 c++ 11个标准,找到了这个例子:

class X2 {
    friend Ct; // OK: class C is a friend
    friend D; // error: no type-name D in scope
    friend class D; // OK: elaborated-type-specifier declares new class
}

根据我对第三个声明的阅读, myfriend class B应该是一个详细的类型说明符,声明一个新的 class

我刚刚开始理解官方标准措辞,所以我一定遗漏了一些东西。我有什么误解?

4

2 回答 2

6

Take a look at 11.3 paragraph 11:

For a friend class declaration, if there is no prior declaration, the class that is specified belongs to the innermost enclosing non-class scope, but if it is subsequently referenced, its name is not found by name lookup until a matching declaration is provided in the innermost enclosing nonclass scope.

Example:

class X;
void a();
void f() {
  class Y;
  extern void b();
  class A {
  friend class X;  // OK, but X is a local class, not ::X
  friend class Y;  // OK
  friend class Z;  // OK, introduces local class Z.
  friend void a(); // error, ::a is not considered
  friend void b(); // OK
  friend void c(); // error
  };
  X *px;           // OK, but ::X is found
  Z *pz;           // error, no Z is found
}
于 2013-01-01T23:06:40.410 回答
5

您的friend class B;声明确实用作前向声明,但在提供匹配声明之前,无法通过名称查找找到此类声明。

[class.friend]/11

If a friend declaration appears in a local class (9.8) and the name specified is an unqualified name, a prior declaration is looked up without considering scopes that are outside the innermost enclosing non-class scope. For a friend function declaration, if there is no prior declaration, the program is ill-formed. For a friend class declaration, if there is no prior declaration, the class that is specified belongs to the innermost enclosing non-class scope, but if it is subsequently referenced, its name is not found by name lookup until a matching declaration is provided in the innermost enclosing nonclass scope.

于 2013-01-01T23:05:51.703 回答