0

我正在尝试制作自己的 BST。我制作了使用模板的类树。

template <class T>
class Tree {
public:
    Tree(void);
    void insert (T key);
private:
    Node<T>* root;
};

在方法 main 我有类似的东西:

Tree<int>* d = new Tree<int>();
int key;
cin >> key;
d->insert(klucz);

我收到一个错误:

函数中引用的未解析外部符号"public: void __thiscall Tree[int]::insert(int)"( )?insert@?$Tree@H@@QAEXH@Z_main

我想知道,如何在不精确类型“关键”字段的情况下从用户那里读取数据。

4

1 回答 1

2

您没有在Tree::insert任何地方定义,但您声明了它。它实际上不存在,因此您需要添加该功能:

//just code to make this example, and be able to compile it
template <class T> class Node
{
private:
    std::vector<T> keys;
public:
    Node()
    {

    }
    size_t Add(T key)
    {
        keys.push_back(key);
        return keys.size() - 1;
    }
};

//tree.h
template <class T>
class Tree {
public:
    Tree(void);
    void insert (T key);
private:
    Node<T>* root;
};

//tree.cpp
template <class T> Tree<T>::Tree (void)
{
    //construction code here
    //example:
    root = new Node<T>;
}

template <class T> void Tree<T>::insert (T key)
{
    //insert code here
    //example:
    root->Add(key);
}

//main.cpp
int main()
{
    Tree<int>* d = new Tree<int>();
    int key;
    std::cin >> key;
    d->insert(key);
    return 0;
}

如果您想读取任何数据并在字符串、整数、双精度数等之间进行转换,那么我建议您查看boost::anyboost::lexical_cast,经过一些修改后,您可以执行以下操作:

template <class T> class Node
{
private:

public:
    std::vector<T> keys;
    Node()
    {

    }
    size_t Add(T key)
    {
        keys.push_back(key);
        return keys.size() - 1;
    }
};

template <class T>
class Tree {
public:
    Tree(void);
    void insert (T key);
    T& get(size_t index);
private:
    Node<T>* root;
};

template <class T> Tree<T>::Tree (void)
{
    //construction code here
    //example:
    root = new Node<T>();
}

template <class T> void Tree<T>::insert (T key)
{
    //insert code here
    //example:
    root->Add(key);
}

template <class T> T& Tree<T>::get (size_t index)
{
    //get code here
    //example:
    return root->keys[index];
}

#include <boost/lexical_cast.hpp>
int main()
{
    Tree<std::string>* d = new Tree<std::string>;
    std::string key;
    std::cin >> key;
    d->insert(key);
    std::cout << "Your input:\n";
    std::cout << "\tString: " << boost::lexical_cast<std::string>(d->get(0)).c_str() << "\n";
    std::cout << "\tFloat: " << boost::lexical_cast<float>(d->get(0)) << "\n";
    std::cout << "\tDouble: " << boost::lexical_cast<double>(d->get(0)) << "\n";
    std::cout << "\tInt: " << boost::lexical_cast<int>(d->get(0)) << "\n";
    return 0;
}

输出:

在此处输入图像描述

于 2013-05-27T00:42:20.587 回答