这是g ++或clang ++中的错误

问题描述 投票:1回答:1

以下代码:

class A
{
  friend class B;
  int m;
};

class B
{
  friend void f(A* p) { p->m = 32; }
};

在clang版本9.0.0-2中进行编译,但在g ++版本9.2.1中则未进行编译

friend-test.cpp: In function ‘void f(A*)’:
friend-test.cpp:10:28: error: ‘int A::m’ is private within this context
   10 |   friend void f(A* p) { p->m = 32; }
      |                            ^
friend-test.cpp:5:7: note: declared private here
    5 |   int m;
      |       ^

哪个编译器是正确的?

c++ g++ clang++
1个回答
1
投票

GCC在右边。 Clang似乎有一个错误。

[[class.friend]

10友谊既不是继承的也不是传递的。 [示例:

class A {
  friend class B;
  int a;
};

class B {
  friend class C;
};

class C  {
  void f(A* p) {
    p->a++;         // error: C is not a friend of A despite being a friend of a friend
  }
};

class D : public B  {
  void f(A* p) {
    p->a++;         // error: D is not a friend of A despite being derived from a friend
  }
};

—例子]

fB的朋友,而B依次是A的朋友并不意味着f被允许访问A的私有部分。

© www.soinside.com 2019 - 2024. All rights reserved.