派生类的朋友可以访问哪些变量

Friend of a derived class can access what variables?

本文关键字:访问 变量 朋友 派生      更新时间:2023-10-16

为了简化我的问题,我有类似的问题:

class Base {
private:
protected:
    int a,b;
    string c;
public:
    [some functions here]
}
class Derived : public Base{
    [some variables and functions]
friend void function();
}
void function(){
int d[a][b];
[stuff]
}

基本上,我的空白功能需要访问基类保护类中的东西。我想将这些变量保留在受保护部分中的定义。无论如何,是否有要与派生类交友的函数,才能访问A和B?

您可以在Derived中定义私有方法:派生中的任何方法都可以访问基本的受保护成员。

函数是派生的朋友,因此它可以在派生中调用那些私人方法,从而访问基本的受保护成员。


编辑以回复下面的评论

get_a()成员方法和a成员数据是其类的成员。这些成员的实例存在于其课程的实例中。除了在一个实例中,它们不存在,因此要访问它们,您需要通过类的实例访问它们。

例如,类似的东西:

class Derived : public Base{
    [some variables and functions]
    friend void function(Derived& derived);
};
void function(Derived& derived)
{
     int a = derived.get_a();
     int b = derived.get_b();
     // I don't know but even the following might work
     int c = derived.a; // able to access field of friend's base class.
}
void test()
{
    Derived* derived = new Derived();
    function(*derived);
    delete derived;
}

您的函数需要通过得出的类的实例访问A和B,如下所示

void function()
{
Derived objectDerived;
int d[objectDerived.a][objectDerived.b];
[stuff]
}