在父级中使用受保护的数据,传递给子级

时间:2011-11-29 02:40:04

标签: c++ oop class inheritance

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

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);
}

1 个答案:

答案 0 :(得分:2)

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

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!
}