如何从私有基类调用静态方法? [英] How to call a static method from a private base class?

查看:51
本文介绍了如何从私有基类调用静态方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于第三方库的布局,我有类似以下代码的内容:

Due to the layout of a third-party library, I have something like the following code:

struct Base
{
    static void SomeStaticMethod(){}
};

struct Derived1: private Base {};

struct Derived2: public Derived1 {
    void SomeInstanceMethod(){
        Base::SomeStaticMethod();
    }
};

int main() {
    Derived2 d2;
    d2.SomeInstanceMethod();

    return 0;
}

我在MSVC中遇到编译器错误C2247:

I'm getting compiler error C2247 with MSVC:

Base :: SomeStaticMethod无法访问,因为Derived1使用private继承了Base.

Base::SomeStaticMethod not accessible because Derived1 uses private to inherit from Base.

由于私有说明符,我知道我无法通过继承从 Derived2 中访问 Base 成员,但是我仍然应该能够调用的静态方法> Base -不管 Base Derived2 之间有任何继承关系.
如何解决歧义并告诉编译器我只是在调用静态方法?

I know I can't access Base members from Derived2 via inheritance because of the private specifier, but I should still be able to call a static method of Base - regardless of any inheritance relationship between Base and Derived2.
How do I resolve the ambiguity and tell the compiler I'm just making a call to a static method?

推荐答案

执行以下操作:

struct Derived2: public Derived1 {
    void SomeInstanceMethod(){
        ::Base::SomeStaticMethod();
//      ^^
//      Notice leading :: for accessing root namespace.
    }
};

这篇关于如何从私有基类调用静态方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆