访问派生类中的受保护成员

访问派生类中的受保护成员

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

我有一个具有受保护成员的基类:

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

它编译并工作得很好。现在我扩展了Base,但仍然希望使用b:

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

请注意,在这种情况下DoSomething仍然引用Base,不是Derived..我希望我仍然可以访问that.b在.内部Derived,但我得到了一个cannot access protected member错误(MSVC 8.0-还没有尝试GCC)。

显然,在b解决了这个问题,但我想知道为什么我不能直接访问b..我认为当您使用公共继承时,受保护的变量对派生类仍然是可见的。


慕莱坞森
浏览 422回答 3
3回答

慕码人2483693

您只能在您的类型(或从您的类型派生的)实例中访问受保护的成员。不能访问父类型或父类型实例的受保护成员。就您的情况而言,Derived类只能访问b成员Derived实例,没有不同之处。Base举个例子。将构造函数更改为接受Derived实例也将解决问题。

杨魅力

如前所述,这只是语言的运作方式。另一个解决方案是利用继承并传递给父方法:class Derived : public Base{   protected:     int d;   public:     void DoSomething(const Base& that)     {       Base::DoSomething(that);       d=0;     }};

白衣染霜花

protected成员可查阅:贯通this指针或相同类型的受保护成员,即使在基中声明。或者来自朋友的课程,函数要解决您的案件,您可以使用最后两个选项之一。在派生中派生的接受:DoSomething或宣告派生friend调至基地:class Derived;class Base{   friend class Derived;   protected:     int b;   public:     void DoSomething(const Base& that)     {       b+=that.b;     }};class Derived : public Base{   protected:     int d;   public:     void DoSomething(const Base& that)     {       b+=that.b;       d=0;     }};在某些情况下,您还可以考虑公共getter。
打开App,查看更多内容
随时随地看视频慕课网APP