2013-10-28 36 views
-1

在BST.h文件我有:C++:我是否正確定義私有函數和公共函數的主體?

class node 
{ 
public: 
node* left; 
node* right; 
int key; 
} 
class BST 
{ 
public: 
void add(int newKey); 
private: 
node* root; 
node* addHelper(node* nd, int newKey); 
}; 

我然後實現在bst.cpp文件中添加和addHelper功能:

#include "BST.h" 

    public void add(int newKey){ 

     addHelper(root,newKey); 

    } 

    node* BST :: addHelper(Node* nd, int newKey) 
    { 
     //do something.. 

    } 

我是否還需要定義我的public add(int newKey)功能: void BST :: add(int newKey)在bst.cpp中?

+0

是的。現在,你聲明'BST :: add',但是定義':: add'。 –

+0

除了Jerry Coffin所說的,「公共」在那裏沒有地方。這是一個語法錯誤。 – juanchopanza

回答

1

是的,因爲您需要指定您正在定義的功能addBST的成員,而不是免費函數add

在下面的例子中,這兩個功能是分開的,即使他們有相同的名字:

void add(int newKey) 
{ 
    // Code to define free function named `add` 
    // - this function is not a member of any class 
} 

void BST::add(int newKey) 
{ 
    // Code to define function named `add` which is member of class `BST` 
} 
1

add功能應該被定義爲:

void BST::add(int newKey){ 

    addHelper(root,newKey); 

} 

訪問說明符是唯一在班級定義中需要。此處需要使用範圍解析運算符,以便與屬於BSTadd()相同。

相關問題