繁体   English   中英

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

[英]Is this a bug in g++ or clang++

以下代码:

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;
      |       ^

哪个编译器是对的?

海湾合作委员会在右边。 Clang 似乎有一个错误。

[班级.朋友]

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 } };

— 结束示例 ]

事实上f是朋友BB是反过来的朋友A并不意味着f被允许访问A的私处。

根据 C++ 17 标准(14.3 朋友)

10 友谊既不是继承的,也不是传递的

因此编译器 clang 有一个错误。

有趣的是,如果在class B之外定义函数,如

class B
{
    public:
    friend void f(A* p);
};

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

那么在这种情况下,编译器 clang HEAD 10.0.0 会发出错误

rog.cc:18:19: error: 'm' is a private member of 'A'
void f(A* p) { p->m = 32; }
                  ^
prog.cc:9:7: note: implicitly declared private here
  int m;
      ^
1 error generated.

所以毫无疑问,编译器有一个错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM