简体   繁体   English

声明受保护的功能朋友

[英]Declaring protected function friend

Does A::foo need to be declared public for B to declare it friend? 请问A::foo需要申报市民B宣布它的朋友吗?

class A {
    protected:  // public ?
        void foo(int x);
};

class B : public A {
    friend void A::foo(int);  // not fine with GCC 4.8.1 but fine with VS 2013
    void goo(int x) {foo(x);}  // fine
    static void hoo(int x) {}
};

void A::foo(int x) {B::hoo(x);}  // friend declaration needed for this

Visual Studio 2013 thinks it is fine if A::foo is protected, but GCC 4.8.1 thinks it's not and wants it to be public. 如果A :: foo受到保护,Visual Studio 2013认为没问题,但GCC 4.8.1认为它不是,并希望它是公开的。 Which compiler is correct? 哪个编译器正确? My initial instinct was that it can be declared protected. 我最初的直觉是它可以被宣布为受保护。 After all, B is derived from A, so should have access to A::foo (as B::goo demonstrates trivially). 毕竟,B是从A派生的,所以应该可以访问A :: foo(因为B :: goo简单地演示)。

VS is correct here . VS在这里是正确的

The name A::foo is in fact accessible in the scope of B since it's publicly derived from A . 事实上,名称A::fooB的范围内是可访问的,因为它是从A公开派生A To prove this, consider 为了证明这一点,请考虑

class A {
    protected:
        void foo(int x);
};

class B : A {
    using A::foo; // it's OK to refer to the name A::foo
};

void A::foo(int x) {}  

So by using the quote § 11.3 [friend functions] 所以使用引用§11.3[朋友功能]

A name nominated by a friend declaration shall be accessible in the scope of the class containing the friend declaration. 朋友声明提名的名称应在包含朋友声明的类的范围内访问。

we can argue that's there's no violation of the rules ( foo is also protected in the derived class). 我们可以争辩说,没有违反规则( foo在派生类中也受到保护)。

It seems like in gcc, once the friend keyword is placed in front of the friend function declaration, name lookup starts ignoring inheritance (nothing to do though with friendship not being inheritable) 看起来像在gcc中,一旦将friend关键字放在友元函数声明的前面,名称查找就会开始忽略继承(虽然友谊不可继承,但无所事事)


As mentioned by 40two in the comments the same error is emitted from Clang and there's a bug report for it ; 正如评论中40two所提到的那样Clang发出了相同的错误,并且有一个错误报告 ; this issue is also reffered to DR209 . 这个问题也提到了DR209 It seems that for the implementers to get this right is quite hard. 对于实施者来说,做到这一点似乎很难。

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

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