使用#include .h文件时无法编译C ++
我有3个文件:linkedStack.cpplinkedStack.h和main.cpp。
g++ -o main linkedStack.cpp main.cpp
我在上面输入命令时无法编译,
但是当我将#include "linkedStack.h"
更改为#include "linkedStack.cpp"
时,它可以工作。
我想知道为什么吗?
linkedStack.h文件如下:
#include <stdio.h>
#include <iostream>
#include <string>
#include <assert.h>
using namespace std;
template <class Type>
class stackADT
{
public:
virtual void push(const Type& newItem)=0;//to add newItem to the stack
virtual Type top() const=0;//to return the top element of the stack
template <class Type>
struct nodeType
{
Type info;
nodeType<Type>*link;
};
template <class Type>
class linkedStackType//:public stackADT<Type>
{
public:
virtual void push(const Type& newItem);//add a new element
linkedStackType();//default constructor
~linkedStackType();//destructor
virtual Type top() const;//return the top element
private:
nodeType<Type>*stackTop;
};
linkedStack.cpp文件如下:
#include "linkedStack.h"
template <class Type>
linkedStackType<Type>::linkedStackType()
{//default constructor
stackTop=NULL;
}
template <class Type>
Type linkedStackType<Type>::top() const
{
assert(stackTop!=NULL);
return stackTop->info;
}//return the top element of the stack ,otherwise terminate the program if the stack is empty
template <class Type>
void linkedStackType<Type>::push(const Type& newItem)
{//add a new element
nodeType<Type>* newNode;
newNode =new nodeType<Type>;
newNode->info=newItem;
newNode->link=stackTop;
stackTop=newNode;
}
main.cpp文件如下:
#include <linkedStack.h>
int main()
{
linkedStackType<int> stack;
stack.push(34);
cout<<stack.top()<<endl;
return 0;
}
结果如下:
g++ -o main linkedStack.cpp main.cpp
Undefined symbols for architecture x86_64:
"linkedStackType<int>::isFullStack() const", referenced from:
vtable for linkedStackType<int> in main0728-bb04be.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)