您没有在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::any或boost::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;
}
输出: