gpt4 book ai didi

c++ - 无法访问 protected 成员

转载 作者:IT老高 更新时间:2023-10-28 22:13:13 27 4
gpt4 key购买 nike

Possible Duplicate:
cannot call base class protected functions?

我不明白以下内容,当 DerivedBase 继承时,它可以访问其 protected 成员,这些成员可以通过 Derived 函数访问。但是,如果 Base 类试图从 Derived 类(它本身允许访问 Base)访问它自己的成员,它就无法访问,为什么?

class Base {
protected:
int x;
};

class Derived : Base {
public:
void foo(Base* b);
};


void Derived::foo(Base* b) {
b->x = 2; // cannot access protected member,
// though Derived inherits from Base, why?
}

最佳答案

一个常见的误解。

Derived::foo() 中,您可以访问Derived 类对象的 protected 基成员。但是,*b 不是 类型的 Derived。相反,它属于 Base 类型,因此它与您的类没有任何关系。

如果您将 Derived* 作为参数,那就不同了——那么您确实可以访问 protected 基成员。


让我们把它拼出来:

struct Derived;

struct Base
{
int f(Derived *);
protected:
int x;
private:
int y;
};

struct Derived : public Base
{
int g(Base *);
int h(Derived *);
};

int Derived::g(Base * b)
{
return b->x; // error, protected member of unrelated class
return b->y; // error, private member of different class
}

int Derived::h(Derived * d)
{
return d->x; // OK, protected base member accessible in derived class
return d->y; // error, private member of different class
}

int Base::f(Derived * d)
{
return d->x; // OK, d converts to Base*
return d->y; // OK, ditto
}

关于c++ - 无法访问 protected 成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7476117/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com