[英]C++ Basic template class constructor
我對與BSTNode類的數據成員有關的對象創建感到困惑。 例如,在頭文件中,數據成員之一被定義為“密鑰k”。 這是否意味着已經創建了默認密鑰,並且我不需要在默認BSTNode構造函數中編寫任何內容,還是仍然需要編寫Key k? 在構造函數中創建默認密鑰? 當我在構造函數中傳遞要設置為k的Key時,這仍然成立嗎?
類定義(在標題中):
class BSTNode {
public:
BSTNode();
BSTNode(Key k, Value v);
Key k;
Value v;
BSTNode* left;
BSTNode* right;
};
這是我的嘗試:
template <class Key, class Value>
BSTNode<Key,Value>::BSTNode(){
Key kk; //create th default key
k = kk; //set the BSTNode's k to the default key
Value vv; //create the default value
v = vv; //set the BSTNode's v to the default value
BSTNode* left = NULL; //set left pointer to NULL
BSTNode* right = NULL; //set right pointer to NULL
}
您的構造函數基本上是無操作的。
讓我們遍歷每一行:
template <class Key, class Value>
BSTNode<Key,Value>::BSTNode(){
Key k; // <--- local variable, destroyed on return
Value v; // <--- local variable, destroyed on return
BSTNode* left = NULL; // <--- local variable initialized to NULL, destroyed on return
BSTNode* right = NULL; // <--- local variable initialized to NULL, destroyed on return
}
您不是在初始化類成員變量,而是在創建新的局部變量並將其設置為值。 構造函數完成后,這些局部變量將不再存在。
您要做的是:
class BSTNode {
public:
BSTNode();
BSTNode(Key theKey, Value theValue) :
Key m_key;
Value m_value;
BSTNode* m_left;
BSTNode* m_right;
};
template <class Key, class Value>
BSTNode<Key,Value>::BSTNode() :
m_key(Key()), m_value(Value()), m_left(0), m_right(0) {}
template <class Key, class Value>
BSTNode(Key theKey, Value theValue) : m_key(theKey), m_value(theValue), m_left(0), m_right(0)
{
//...
}
注意構造的0參數版本初始化鍵和值到任何默認的初始值是的Key
和Value
類型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.