[英]Using templates with C++
我正在嘗試使用模板實現一棵紅黑樹。 insert函數采用兩種通用類型,即Item和Key。 但是,當我在main()中創建RedBlackTree的實例並調用函數“ InsertKey”時,程序給出了錯誤:無法解析方法“ InsertKey”。 另外,我不知道在“ InsertKey”函數中作為參數傳遞什么。 我實現了一個由隨機元素組成的數組。 數組應該是參數之一,但是我不知道另一個參數是什么。
這是我的頭文件:
#ifndef REDBLACKTREE_H_
#define REDBLACKTREE_H_
template <class Item, class Key>
class RedBlackTree
{
typedef enum
{
BLACK,
RED
}ColourNode;
/* user data stored in tree */
typedef struct {
int data;
} treedata;
typedef struct RBT
{
struct RBT *left;
struct RBT *right;
struct RBT *parent;
struct RBT *root;
ColourNode colour;
//Item item;
Key key;
treedata data;
}RBTNode;
public:
~RedBlackTree(); // destructor
RedBlackTree(Item, Key); // default constructor
void InsertKey(const Item *&, const Key *&);
void FixingInsert(const Item *&, const Key *&);
int RemoveKey(Item, Key);
int FindKey(Item, Key);
//private:
//RedBlackTree<Item, Key> *rootPointer;
};
#endif /* REDBLACKTREE_H_ */
這是我的main()
#include <iostream>
#include <string>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include "RedBlackTree.h"
using namespace std;
int main(int argc, const char* argv[])
{
const int arraysize = 200;
int arr[arraysize];
RedBlackTree<int, int> t1(int, int);
srand((unsigned)time(0));
for(int i = 0; i <= arraysize-1; i++)
{
arr[i] = rand() % 210;
//printf("%d ", arr[i]);
}
for(int i = 0; i <= arraysize-1; i++)
{
t1.InsertKey(arr[i], // something else//); //InsertKey should have another parameter, but for now I am trying to figure out why it cannot be resolved.
}
}
另外,對其他可能的東西有什么想法嗎? 我不知道該通過什么。
RedBlackTree<int, int> t1(int, int);
在這里,您聲明了一個名為t1
的函數,該函數返回RedBlackTree<int, int>
並接受兩個均為int
類型的參數。
我認為您實際上想創建一個RedBlackTree<int, int>
對象並將其稱為t1
。 它有一個構造函數,需要一個Item
和一個Key
。 但是,您已經評論它說它是默認構造函數,而事實並非如此。 默認構造函數是不帶任何參數的構造函數。 我認為您的意思是這樣聲明構造函數:
RedBlackTree(); // default constructor
然后,您可以創建這種類型的對象,如下所示:
RedBlackTree<int, int> t1;
您永遠不會在(int, int)
這樣的普通括號之間傳遞類型。 它們總是放在尖括號之間,例如<int, int>
並在模板名稱之后。 在這種情況下,模板名稱為RedBlackTree
,我們想使用int
類型實例化它,因此我們執行RedBlackTree<int, int>
。 沒有什么要傳遞給構造函數的。
RedBlackTree<int, int> t1(int, int);
被視為函數聲明。 您尚未為RedBlackTree
定義默認的構造函數,因此您必須提供一個默認構造函數,或使用參數構造對象。
RedBlackTree() { }
下一個問題是,當您只給InsertKey
一個函數簽名時,它的函數簽名需要兩個參數。
void InsertKey(const Item *&, const Key *&);
t1.InsertKey(arr[i], /* something else must go here */)
int
當您的函數需要一個int *&
時,您正在傳遞一個int
。 如果您打算通過const-reference傳遞這些參數,請刪除星號。
void InsertKey(const Item &, const Key &);
否則,您需要傳遞一個指針。
t1.InsertKey(&arr[i], /* something else */);
問題在於它需要一個const
指針,因此您必須執行以下操作:
const int* pointer = &arr[i];
t1.InsertKey(pointer, /* something else */);
您向用戶承諾了一個InsertKey()
兩個指針的函數InsertKey()
。 您嘗試改為使用一個值調用InsertKey()
。 那不會飛。
作為一般建議,在將數據結構轉換為模板之前,請確保其數據結構適用於具體類型(對於算法而言,這是另一種方法)。 我還建議您RedBlackTree<K, V>
用K
和V
對象而不是使用指針旅行。 如果用戶確實想使用指針,則可以通過指定指針參數來使用類模板。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.