我在 VS 中遇到 LNK 2019 错误。
我已经阅读了几个类似的问题,但无法理解我应该做什么。据我所知,由于某种原因 VS 无法找到模板类代码。我不确定。
#include "pch.h"
#include <iostream>
#include <assert.h>
template<typename T>
struct item {
item* pointer = nullptr;
T value;
};
template <typename T>
class stack {
private:
item<T>* top;
public:
stack() { top = nullptr; };
~stack();
void push(const T& s) {
item<T>* p = top;
top = new item<T>;
assert(top != nullptr);
top->value = s;
top->pointer = p;
std::cout << "The item has been pushed." << std::endl;
}
void pop() {
T s;
if (!top) {
std::cout << "The stack is empty." << std::endl;
}
else {
s = top->value;
item<T>* p = top;
top = top->pointer;
delete p;
std::cout << "The item has been popped." << std::endl;
}
};
void check() {
if (!top) { std::cout << "The stack is empty." << std::endl; }
else { std::cout << "It has elements in it." << std::endl; }
}
};
int main()
{
stack<int> test;
return 0;
}
我希望之后能够推送和弹出元素。这样我就可以继续我的项目。
最佳答案
你在这里为 stack
声明了一个析构函数:
~stack();
但你没有定义它。将上面的改成
~stack() { /* Clean up resources here. */ }
它应该可以工作。
关于c++ - 当所有内容都在一个文件中时,为什么我会收到链接器错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56946506/