2011-11-29 24 views
1

如何在傳入派生類時訪問父級類中的數據,該類是受保護的。在父級中使用受保護數據,傳入子級

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

只是'a + = 1'。基礎成員成爲你班級的一部分。 –

+0

請提供一個實際顯示您正在嘗試執行的代碼示例,其中不包含無關錯誤(即addOne(a)不是有效的調用)。 –

+0

對不起,解決了。我想要做的是從一個子類中編輯父類中的二叉樹。 (一個父類聲明,一個子類聲明)。我周圍的工作是在將二進制樹頭指針傳遞給子代的父級封裝函數中。 – CornSmith

回答

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

謝謝!我沒有意識到我可以用這種方式打破其他孩子。我redid我的算法,以便父類管理我需要的數據,即使它不是很有意義的父。這比打破面向對象的規則要好。 ++ Martinho – CornSmith

+0

@CornSmith請查看我的輕微編輯。我以前犯過一個錯誤。您不限於當前的*實例*,而是限於當前*類型*的指針/引用。一個類型知道它自己的不變式,所以它可以安全地操作該類型的其他實例(模塊錯誤)。例如,這個作品http://www.idene.com/8LvA3 –

+0

@ R-Martinho-Fernandes 所以你說一個孩子類可以編輯另一個孩子類的父母的變量,如果它是相同的類型。謝謝你的提示! (和ideone上的好代碼,那是超出和超出的) – CornSmith

相關問題