嗨我遇到一些问题,当我尝试编译我的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;
}