[問題] template class編譯問題
開發平台(Platform): Windows 10
編譯器:MinGW G++
額外使用到的函數庫(Library Used): No
問題(Question):
我在練習data structure linked list,目前有四個檔案,分別是:
SLinkedList.h, SLinkedList.cpp, SNode.h, main.cpp
code在底下。
餵入的資料(Input):
compile command:g++ main.cpp SLinkedList.cpp
預期的正確結果(Expected Output):
正確編譯產生a.exe檔
錯誤結果(Wrong Output):
...\AppData\Local\Temp\cceyYWGl.o:main.cpp:(.text+0x16):
undefined reference to `SLinkedList<std::string>::SLinkedList()'
...\AppData\Local\Temp\cceyYWGl.o:main.cpp:(.text+0x26):
undefined reference to `SLinkedList<std::string>::~SLinkedList()'
collect2.exe: error: ld returned 1 exit status
程式碼(Code):(請善用置底文網頁, 記得排版)
================================
SLinkedList.h
================================
#include "SNode.h"
#ifndef SLINKEDLIST_H
#define SLINKEDLIST_H
template<typename E>
class SLinkedList {
public:
SLinkedList();
~SLinkedList();
bool empty() const;
const E& front() const;
void addFront(const E& e);
void removeFront();
private:
SNode<E>* head;
};
#endif
================================
SLinkedList.cpp
================================
#include "SLinkedList.h"
#include <stddef.h>
template<typename E>
SLinkedList<E>::SLinkedList()
: head(NULL) { }
template<typename E>
SLinkedList<E>::~SLinkedList() {
while (!empty()) removeFront();
}
template<typename E>
bool SLinkedList<E>::empty() const {
return head == NULL;
}
template<typename E>
const E& SLinkedList<E>::front() const {
return head->elem;
}
template<typename E>
void SLinkedList<E>::addFront(const E& e) {
SNode<E>* v = new SNode<E>;
v->elem = e;
v->next = head;
head = v;
}
template<typename E>
void SLinkedList<E>::removeFront() {
SNode<E>* old = head;
head = old->next;
delete old;
}
================================
SNode.h
================================
#ifndef SNODE_H
#define SNODE_H
template<typename E>
class SLinkedlist;
template <typename E>
class SNode {
private:
E elem;
SNode<E>* next;
friend class SLinkedlist<E>;
};
#endif
================================
main.cpp
================================
#include "SLinkedList.h"
#include <iostream>
using namespace std;
int main() {
SLinkedList<string> b;
return 0;
}
補充說明(Supplement):
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 123.193.48.28
※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1487511534.A.826.html
→
02/19 21:45, , 1F
02/19 21:45, 1F
推
02/19 21:46, , 2F
02/19 21:46, 2F
→
02/19 21:46, , 3F
02/19 21:46, 3F
→
02/19 21:56, , 4F
02/19 21:56, 4F
C_and_CPP 近期熱門文章
PTT數位生活區 即時熱門文章
13
34
30
49