繁体   English   中英

声明受保护的功能朋友

[英]Declaring protected function 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

如果A :: foo受到保护,Visual Studio 2013认为没问题,但GCC 4.8.1认为它不是,并希望它是公开的。 哪个编译器正确? 我最初的直觉是它可以被宣布为受保护。 毕竟,B是从A派生的,所以应该可以访问A :: foo(因为B :: goo简单地演示)。

VS在这里是正确的

事实上,名称A::fooB的范围内是可访问的,因为它是从A公开派生A 为了证明这一点,请考虑

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) {}  

所以使用引用§11.3[朋友功能]

朋友声明提名的名称应在包含朋友声明的类的范围内访问。

我们可以争辩说,没有违反规则( foo在派生类中也受到保护)。

看起来像在gcc中,一旦将friend关键字放在友元函数声明的前面,名称查找就会开始忽略继承(虽然友谊不可继承,但无所事事)


正如评论中40two所提到的那样Clang发出了相同的错误,并且有一个错误报告 ; 这个问题也提到了DR209 对于实施者来说,做到这一点似乎很难。

暂无
暂无

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

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