我在使用以下程序时遇到了一些问题。该程序使用链表实现堆栈。我没有在此处显示我的所有代码,因为代码很好。但我遇到的问题是链接不同的文件放在一起。
我正在使用 IDE 来运行程序。当我运行 TestIntStacks.cpp
时,主要方法应该从 StackFunctions.cpp
调用 test()
。测试函数(在 StackFunctions.cpp
中定义)使用 TestStack
类方法。
目前我收到一条错误消息,提示“链接器错误,推送/弹出未定义”。我做错了什么?我确定这与 namespace 有关。
MyStack.h
-------------------------------------
namespace A
{
class Node{
public :
char data;
StackNode* link;
StackNode(int v=0): data(v), link(NULL){ }
};
class MyStack{
private:
Node * top;
public:
MyStack():top(NULL){ }
void push(int c);
};
}//namespace
//TestStack.cpp
--------------------------------------------------------------
#include "MyStack.h"
namespace A
{
void MyStack::push(int x)
{
StackNode *temp = new StackNode(x);
temp->link = top;
top = temp;
}
}
//StackFunctions.cpp
-----------------------------------------------------------
#include <iostream>
#include "TestStack.h"
using namespace std;
using namespace A;
void test()
{
MyStack st;
st.push(1);
st.push(2);
st.push(3);
st.push(4);
}
// TestIntStacks.cpp
----------------------------------------------------------------
// Code for testing the TestStack
// from the A namespace.
#include <iostream>
#include <vector>
using namespace std;
#include "TestStack"
#include "StackFunctions.cpp"
void test();
int main()
{
test();
system("pause");
return 0;
}
最佳答案
您在头文件 TestStack.h 中定义了 push()
和 pop(
) 方法,但是您没有在 TestStack.cpp 中为它们提供实现。您需要添加对对象执行推送和弹出操作的代码。
关于C++ 链接器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5045287/