c – 访问受保护嵌套类的朋友

我有以下C代码:

class A {
 protected:
  struct Nested {
    int x;
  };
};

class B: public A {
  friend class C;
};

class C {
  void m1() {
    B::Nested n; // or A::Nested
  }
};

使用g 4.4编译这个片段,我在m1中使用B :: Nested还是A :: Nested没有区别. Clang接受B :: Nested,但如果我是A :: Nested则不编译.这是g或clang中的错误吗?

解决方法:

根据该标准,GCC是正确的,Clang是错的.它在11.2 / 4说

A member m is accessible when named in class N if

  • m as a member of N is protected, and the reference occurs in a member or friend of class N, or in a member or friend of a class P derived from N, where m as a member of P is private or protected

这是这个Clang bugreport的主题,它阻止了Clang构建Qt:http://llvm.org/bugs/show_bug.cgi?id=6840.一个Clang家伙说

Actually, I intentionally haven’t implemented this rule yet. It is either a
drafting error or a horrible mistake. It neuters the entire ‘protected’
specifier, it makes the well-formedness of code dependent on the
existence of completely unrelated classes, it imposes high costs on the
implementation, and it’s formally undecidable in the presence of templates.

上一篇:c-朋友函数和名称空间.无法访问班级中的私人成员


下一篇:CF70D Professor's task