您無法通過指針/對基類的引用訪問受保護的數據。這是爲了防止您打破其他派生類對該數據可能具有的不變量。
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!
}
只是'a + = 1'。基礎成員成爲你班級的一部分。 –
請提供一個實際顯示您正在嘗試執行的代碼示例,其中不包含無關錯誤(即addOne(a)不是有效的調用)。 –
對不起,解決了。我想要做的是從一個子類中編輯父類中的二叉樹。 (一個父類聲明,一個子類聲明)。我周圍的工作是在將二進制樹頭指針傳遞給子代的父級封裝函數中。 – CornSmith