【问题标题】:Using protected data in a parent, passed into a child class在父类中使用受保护的数据,并传递给子类
【发布时间】:2011-11-29 02:40:03
【问题描述】:

当传递到派生类时,如何访问受保护的父类中的数据。

class parent
{ 
    protected:
        int a;
};

class child : public parent
{
    void addOne(parent * &);
};

void child::addOne(parent * & parentClass)
{
    parentClass->a += 1;
}

int main()
{
    parent a;
    child b;

    parent* ap = &a;

    b.addOne(ap);
}

【问题讨论】:

  • 只是a += 1。基础成员成为您班级的一部分。
  • 请提供一个代码示例,实际显示您正在尝试执行的操作,并且不包含不相关的错误(即addOne(a) 不是有效调用)。
  • 抱歉,已解决。我要做的是从子类编辑父类中的二叉树。 (声明了一个父类,声明了一个子类)。我的解决方法是父级中的一个包装函数,它将二叉树头指针传递给子级。

标签: c++ oop class inheritance


【解决方案1】:

您不能通过指向基类的指针/引用来访问受保护的数据。这是为了防止您破坏其他派生类可能对该数据具有的不变量。

class parent
{
    void f();
    // let's pretend parent has these invariants:
    // after f(), a shall be 0
    // a shall never be < 0.

    protected:
        int a;
};

class child : public parent
{
public:
    void addOne(parent * &);
};


class stronger_child : public parent
{
public:
    stronger_child(int new_a) {
        if(new_a > 2) a = 0;
        else a = new_a;
    }
    // this class holds a stronger invariant on a: it's not greater than 2!
    // possible functions that depend on this invariant not depicted :)
};

void child::addOne(parent * & parentClass)
{
    // parentClass could be another sibling!
    parentClass->a += 1;
}

int main()
{
    stronger_child a(2);
    child b;

    parent* ap = &a;

    b.addOne(ap); // oops! breaks stronger_child's invariants!
}

【讨论】:

  • 谢谢!!我没有意识到我可以用这种方式伤害其他孩子。我重新编写了我的算法,以便父类管理我需要的数据,即使它对父类不太有意义。这比打破 OO 规则要好。 ++马蒂尼奥
  • @CornSmith 请查看我的轻微编辑。我之前犯了一个错误。您不限于当前的instance,而是当前type 的指针/引用。一个类型知道它自己的不变量,因此它可以安全地操作该类型的其他实例(模数错误)。例如,这适用于ideone.com/8LvA3
  • @R-Martinho-Fernandes 所以你说一个子类可以编辑另一个子类的父类变量,如果它是相同的类型。谢谢你的提示! (以及 ideone 上的漂亮代码,超越了)
  • 希望child不会破坏stronger_child不变量。
  • @curiousguy 对不起,我不明白。你是什​​么意思?这不是我在回答中显示的吗?
猜你喜欢
  • 2010-11-27
  • 2011-10-09
  • 1970-01-01
  • 1970-01-01
  • 2013-12-28
  • 2015-07-18
  • 2016-07-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多