访问派生类中的受保护成员 [英] Accessing protected members in a derived class

查看:189
本文介绍了访问派生类中的受保护成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我昨天遇到了一个错误,虽然很容易解决,我想确保我理解C ++正确。

I ran into an error yesterday and, while it's easy to get around, I wanted to make sure that I'm understanding C++ right.

我有一个基地class with a protected member:

I have a base class with a protected member:

class Base
{
  protected:
    int b;
  public:
    void DoSomething(const Base& that)
    {
      b+=that.b;
    }
};

这个编译和工作很好。现在我扩展Base但仍想使用b:

This compiles and works just fine. Now I extend Base but still want to use b:

class Derived : public Base
{
  protected:
    int d;
  public:
    void DoSomething(const Base& that)
    {
      b+=that.b;
      d=0;
    }
};

请注意,在这种情况下 DoSomething 引用 Base ,而不是 Derived 。我希望我仍然可以访问里面里面的 that.b ,但我得到一个无法访问受保护的成员错误(MSVC 8.0 - 尚未尝试过gcc)。

Note that in this case DoSomething is still taking a reference to a Base, not Derived. I would expect that I can still have access to that.b inside of Derived, but I get a cannot access protected member error (MSVC 8.0 - haven't tried gcc yet).

显然, code> b 解决了问题,但我想知道为什么我不能直接访问 b

Obviously, adding a public getter on b solved the problem, but I was wondering why I couldn't have access directly to b. I though that when you use public inheritance the protected variables are still visible to the derived class.

推荐答案

你只能访问受保护的成员在您的类型实例中(或派生自您的类型)。

您无法访问父类或表兄弟类型实例的受保护成员。

You can only access protected members in instances of your type (or derived from your type).
You cannot access protected members of an instance of a parent or cousin type.

在你的情况下, Derived 类只能访问 Derived 的 b code>实例,而不是不同的 Base 实例。

In your case, the Derived class can only access the b member of a Derived instance, not of a different Base instance.

更改构造函数以获取 Derived 实例也会解决问题。

Changing the constructor to take a Derived instance will also solve the problem.

这篇关于访问派生类中的受保护成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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