1. 程式人生 > 實用技巧 >C++ error LNK2019: 無法解析的外部符號

C++ error LNK2019: 無法解析的外部符號

問題描述:1.用Stack.h描述Stack類的定義,用Stack.cpp實現Stack.h定義的函式,在9_9.cpp裡呼叫,但是編譯時會報 “error LNK2019: 無法解析的外部符號”的錯

1.Stack.h的程式碼如下

//Stack.h
#ifndef STACK_H
#define STACK_H
#include<iostream>
#include<cassert>
template<class T,int SIZE=50>
class Stack {
private:
    T list[SIZE];
    
int top; public: Stack(); void push(const T& item); T pop(); void clear(); const T& peek()const; bool isEmpty()const; bool isFull()const; }; #endif // !STACK_H

2.Stack.cpp程式碼如下

 1 #include"Stack.h"
 2 #include<iostream>
 3 using namespace std;
 4 template<class
T, int SIZE> 5 Stack<T, SIZE>::Stack() { 6 top = -1; 7 } 8 9 template<class T, int SIZE> 10 void Stack<T, SIZE>::push(const T& item) { 11 assert(!isFull()); 12 top++; 13 list[top] = item; 14 } 15 16 template<class T, int SIZE> 17 T Stack<T, SIZE>::pop() {
18 assert(!isEmpty()); 19 return list[top--]; 20 } 21 22 template<class T, int SIZE> 23 const T& Stack<T, SIZE>::peek() const { 24 assert(!isEmpty()); 25 return list[top]; 26 } 27 28 template<class T, int SIZE> 29 void Stack<T, SIZE>::clear() { 30 top = -1; 31 } 32 33 template<class T, int SIZE> 34 bool Stack<T, SIZE>::isEmpty()const { 35 return top == -1; 36 } 37 38 template<class T, int SIZE> 39 bool Stack<T, SIZE>::isFull()const { 40 return top == SIZE - 1; 41 }

3.9_9.cpp程式碼如下

#include<iostream>
#include"Stack.h"

using namespace std;

int main() {
    /*Calculator c;
    c.run();*/
    Stack<double,50> s;
    s.push(3.3);
    cout << s.pop() << endl;
    return 0;
}

網上很多說時沒有引進庫或模板和模板類的定義不在同一資料夾下面,然而試了半天還是出現同樣的錯誤,百思不得其解。

4)暫時解決方法,將Stack.cpp的函式定義寫在Stack.h裡。等有時間再看看問題究竟出現在哪。

error LNK2019: 無法解析的外部符號