gpt4 book ai didi

c++ - 从派生类的 friend 那里使用基类的 protected 静态函数

转载 作者:行者123 更新时间:2023-11-30 03:52:32 24 4
gpt4 key购买 nike

不同的编译器似乎对这个问题有不同的看法。以下代码在 gcc 下编译良好,但在 clang 下编译失败:

class Base {
protected:
static void f() {}
};

class Derived : public Base {
friend class DerivedFriend;
};

class DerivedFriend {
public:
void g() {
Base::f();
}
};

clang 的错误是:

main.cpp:13:15: error: 'f' is a protected member of 'Base'
Base::f();
^
main.cpp:3:17: note: declared protected here
static void f() {}
^
1 error generated.

最佳答案

这是 CWG issue 1873 ,这改变了这种情况的规则([class.access.base]/p5):

A member m is accessible at the point R when named in class N if

  • [...]
  • m as a member of N is protected, and R 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 public, private, or protected, or
  • [...]

这里,NBasePDerivedmf()R出现在DerivedFriend的成员中;在 CWG1873 之前,这是允许的,但 CWG1873 删除了“派生类的友元”案例,并使其格式错误。

解决方法是将 f 引用为 Derived 的成员,而不是 Base

关于c++ - 从派生类的 friend 那里使用基类的 protected 静态函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30626288/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com