如何在传递到派生类时访问受保护的父类中的数据。
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);
}
答案 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!
}