gpt4 book ai didi

c++ - 当你是 friend 时,为什么 GCC 不允许从私有(private)嵌套类继承?

转载 作者:可可西里 更新时间:2023-11-01 16:39:18 24 4
gpt4 key购买 nike

问同样的问题:为什么 GCC 允许从私有(private)嵌套类继承?对于非模板类,它允许从私有(private)嵌套类继承,如果它是一个 friend ,但不是模板类。是错误吗?

template<class Base>
class InheritFromBaseMember : public Base::MemberPrivate // error
{
using PrivateMember = typename Base::MemberPrivate; // works fine
};

class MyBase{
friend class InheritFromBaseMember<MyBase>;

// another try to declare it friend
template<class T>
friend class InheritFromBaseMember;

friend class AnotherClass;

class MemberPrivate{};
};

class AnotherClass : public MyBase::MemberPrivate{}; // works fine

int main() {
InheritFromBaseMember<MyBase>{};
}

来自 g++ 5.3.0 的错误消息:

error: 'class MyBase::MemberPrivate' is private
class MemberPrivate{};
^
error: within this context
class InheritFromBaseMember : public Base::MemberPrivate // error
^

最佳答案

这绝对是一个 gcc 错误。 gcc 有 lots of issues与友元和模板。这个例子几乎完全出现在标准中,在 [class.friend] 下,强调我的:

Declaring a class to be a friend implies that the names of private and protected members from the class granting friendship can be accessed in the base-specifiers and member declarations of the befriended class.
[ Example:

class A {
class B { };
friend class X;
};

struct X : A::B { // OK: A::B accessible to friend
A::B mx; // OK: A::B accessible to member of friend
class Y {
A::B my; // OK: A::B accessible to nested member of friend
};
};

—end example ]

关于c++ - 当你是 friend 时,为什么 GCC 不允许从私有(private)嵌套类继承?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37487609/

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