我正在尝试编写一个利用c ++模板的LinkedList类。
理想情况下,我希望能够实现std :: vector ...
vector<int> nums;
nums.push_back(4);
vector<string> words;
words.push_back("blah");
我已经实现了LinkedList类,但是当我尝试调用方法时,出现了未定义的引用错误...
/ home / user / src / c ++ / main.cpp:158:未定义的引用 `LinkedList :: Add(int)'
我的LinkedList类如下。...
template<typename T>
struct Node {
T value;
Node* next;
Node(T _value) : value(_value) , next(nullptr) {}
};
template<typename T>
class LinkedList {
public:
public:
LinkedList() : m_root(nullptr) {}
void Add(T value);
std::string ToString() const;
public:
Node<T>* m_root;
};
cpp
#include "LinkedList.h"
#include <iostream>
#include <sstream>
template<class T>
void LinkedList<T>::Add (T value)
{
Node<T>* newNode = new Node<T>(value);
if (m_root == nullptr) {
m_root = newNode;
return;
}
Node<T>* endNode = m_root;
while (endNode->next != nullptr)
endNode = endNode->next;
endNode->next = newNode;
}
template<class T>
std::string LinkedList<T>::ToString () const
{
std::stringstream ss;
Node<T>* node = m_root;
while (node != nullptr) {
ss << node->value;
ss << ' ';
node = node->next;
}
ss << '\n';
return ss.str();
}