2016-05-30 56 views
0

嗨我遇到一些問題,當我嘗試編譯我的3個文件,main.cpp,My_Stack.cpp和My_Stack.hpp如果我沒有包含頭文件,並且在main.cpp中添加了「#include」My_Stack.cpp「」而不是「#include」My_Steak.hpp「」,那麼「Undefined symbols for architecture x86_64」錯誤精細。未定義的符號體系結構x86_64錯誤在c + +中,頭顯然沒有鏈接


//main.cpp 
#include <iostream> 
#include "My_Stack.hpp" 

int main(int argc, const char * argv[]) { 
    My_Stack<int> s = My_Stack<int>(); 
    s.push(1); 
    s.push(2); 
    cout << s.pop() << endl; 
    cout << s.pop() << endl; 


} 

//My_Stack.hpp 
#ifndef My_Stack_hpp 
#define My_Stack_hpp 

#include <stdio.h> 

#include <string> 

using namespace std; 

template<class T> 
class My_Stack { 

public: 
    My_Stack(); 
    void push(T v); 
    T pop(); 

private: 
    class My_Stack_Node { 
    public: 
     T data; 
     My_Stack_Node* next; 
     My_Stack_Node(T n) { 
      data = n; 
      next = NULL; 
     } 
    }; 
    My_Stack_Node* head; 

}; 


#endif /* My_Stack_hpp */ 

//My_Stack.cpp 
#include "My_Stack.hpp" 

#include <string> 
#include <sstream> 

using namespace std; 

template<class T> 
My_Stack<T>::My_Stack() { 
    this->head = NULL; 
} 

template<class T> 
void My_Stack<T>::push(T v) { 
    if (this->head == NULL) { 
     this->head = new My_Stack_Node(v); 
    } 
    else { 
     My_Stack_Node* aux = new My_Stack_Node(v); 
     aux->next = this->head; 
     this->head = aux; 
    } 
} 

template<class T> 
T My_Stack<T>::pop() { 
    My_Stack_Node* aux = this->head; 
    this->head = this->head->next; 
    return aux->data; 
} 

回答

0

模板定義必須往裏走相應My_Stack.cpp頭文件即定義必須內My_Stack.hpp放。

推薦你去在常見問題解答:
https://isocpp.org/wiki/faq/templates#separate-template-fn-defn-from-decl

從常見問題粘貼相關部分:

模板是不是一個類或函數。模板是編譯器用來生成一系列類或函數的「模式」 。

爲了讓編譯器生成代碼 它必須同時看到模板定義(不僅僅是聲明)和用於「填充」模板的特定類型。對於 示例,如果您嘗試使用Foo,編譯器必須同時看到 Foo模板以及您試圖製作特定Foo的事實。

您的編譯器在編譯另一個.cpp文件時可能不記得一個.cpp文件的細節 。 它可以,但大多數不會,如果你正在閱讀這個FAQ,它幾乎沒有 。順便說一下,這被稱爲「單獨編輯 模型。」

相關問題