c++ - #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)
解决方案
推荐阅读
- amazon-web-services - 我们可以在 AWS 中更改 SSH 证书的区域或从一个区域移动到另一个区域吗?
- html - Plotly Dash 不能将 div 放在同一行
- javascript - 否定时未正确分配在 process.env (process.env.FLIP_FLOP) 上设置的环境变量 (!process.env.FLIP_FLOP)
- php - Laravel:Jasper 在 laravel lumen5.6 中报告
- asp.net - 加载视图时出现 MVC 错误:错误。处理您的请求时发生错误
- android - 地理编码器语言环境总是返回英文
- c# - 是否可以将 MultiBinding 的 targetType 传递给子绑定的转换器?
- reactjs - 哪个最好使用 Redux-thunk 或 redux-saga
- reactjs - 如何显示存储在数组中的图像
- linux - 使用变量作为文件名时 ripMIME 不起作用