首页 > 解决方案 > #include .h 文件时编译失败,但 #include .cpp 文件时编译成功

问题描述

使用#include .h 文件时无法编译 C++

我有 3 个文件:linkedStack.cpp linkedStack.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)

标签: c++

解决方案


推荐阅读