我想知道從公共函式呼叫私有函式以實作更簡潔的語法是否會導致任何型別的問題。
#include<iostream>
class tree{
private:
struct node {
int data;
int counter = 1;
node* left;
node* right;
};
node* getnewnode(int x) {
node* temp = new node();
temp -> data = x;
temp -> left = NULL;
temp -> right = NULL;
return temp;
}
node* recursiveinsert(int x, node* rootPtr) {// recursively insert a new node
if(rootPtr==NULL) { // if the tree is empty, append the new node
rootPtr = getnewnode(x);
}
else if(x <= rootPtr->data){ // if x is lesser than the node value, make a recursive call with the left subtree as root
rootPtr -> left = recursiveinsert(x, rootPtr -> left);
}
else { //if x is greater than the node value, make a recursive call with the right subtree as root
rootPtr -> right = recursiveinsert(x, rootPtr -> right);
}
return rootPtr;
}
public:
//store address of root node
node* root = NULL;
void insert(int x) {
root = recursiveinsert(x, root);
}
};
使用樹類,而不是在 main 中呼叫:
int main(){
tree t;
t.root = t.recursiveinsert(10, t.root);
}
我認為這樣稱呼它會更干凈:
int main(){
tree t;
t.insert(10);
}
這是一個好的編碼習慣嗎?
uj5u.com熱心網友回復:
對于初學者,資料成員
node* root = NULL;
不得公開。
其次,該函式recursiveinsert應至少宣告為靜態成員函式。
最好像這樣宣告和定義它
static void recursiveinsert( node * &rootPtr, int x )
{
if ( rootPtr == nullptr )
{
rootPtr = getnewnode(x);
}
else if ( x < rootPtr->data )
{
recursiveinsert( rootPtr -> left, x );
}
else
{
recursiveinsert( rootPtr -> right, x );
}
}
從公共成員函式呼叫私有成員函式并沒有錯。例如,當類的建構式呼叫其 mem-initializer 串列中的私有成員函式時,這種情況并不少見。
該功能getnewnode可以看起來更簡單。例如
node* getnewnode( int x)
{
return new node { x, 1, nullptr, nullptr };
}
uj5u.com熱心網友回復:
您可能還想隱藏“根”成員,以便直接設定它甚至是不可能的。然后有一個訪問器,如:
const node * GetRoot () { return node; }
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/498104.html
上一篇:如何在C 類中合并具有相同邏輯的不同運算子而不進行復制粘貼
下一篇:PHP使用替代類(如果存在)
