简体   繁体   English

无法使用朋友类从基类访问私有成员

[英]Cannot access private members from base class using friend classes

This is my code: 这是我的代码:

class Base
{
    friend class SubClass;
    int n;
    virtual int getN()
    {
        return n;
    }
};

class SubClass: public Base
{
public:
    SubClass() {}
    SubClass(const SubClass& s) {}


};

int _tmain(int argc, _TCHAR* argv[])
{
    SubClass s;
    int x = s.getN();

    return 0;
}


error C2248: 'Base::getN' : cannot access private member declared in class 'Base'

What more do I have to do to access my private members from Base ? 要从Base访问我的私人成员,我还需要做什么?

Your friend declaration means that SubClass gets to access it in the scope of SubClass . 您的friend声明意味着SubClass可以SubClass范围内访问它。

If you want users of a class to access something, at some point you need to a write public: function: 如果要让类的用户访问某些内容,则有时需要编写public:函数:

class SubClass : public Base
{
public:
    int getN()
    {
        return Base::getN();
    }
};

You can write a using declaration to bring a base class function into the current class: 您可以编写using声明,将基类函数带入当前类:

class SubClass : public Base
{
public:
    // getN is considered declared at this point now (in public)
    using Base::getN(); 
};

为什么不将n声明为protected呢?

The code in main is not trying to access a SubClass method, it's trying to access a Base method - that's why it doesn't work. main的代码不是试图访问SubClass方法,而是试图访问Base方法-这就是为什么它不起作用的原因。

Try adding an override in SubClass : 尝试在SubClass添加替代:

virtual int getN()
{
    return Base::getN();
}

getN() is never made public, so tmain() can't call it. getN()从未公开,因此tmain()不能调用它。

Make a sub class a friend of a base class is not the right way to do this anyway. 无论如何,让子类成为基类的朋友不是正确的方法。 It is a confusing subversion of the type system. 这是类型系统的一个令人困惑的颠覆。 If you want to access non-public members of a base class from a sub class but not have them public, make them protected. 如果要从子类访问基类的非公共成员,但又不公开它们,则将其保护。

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

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