C++模板错误
可能的重复:
模板方法未定义引用错误
你好,我有这段代码给了我这个错误:
未定义对 `MyStack::push(int)' main.cpp 的引用
为什么?
MyStack.h:
#ifndef STACK_H
#define STACK_H
template <typename T>
class MyStack
{
private:
T *stack_array;
int count;
public:
void push(T x);
void pop(T x);
void xd(){}
};
#endif /* STACK_H */
MyStack.cpp:
#include "mystack.h"
template <typename T>
void MyStack<T>::push(T x)
{
T *temp;
temp = new T[count];
for(int i=0; i<count; i++)
temp[i] = stack_array[i];
count++;
delete stack_array;
stack_array = new T[count];
for(int i=0; i<count-1; i++)
stack_array[i] = temp[i];
stack_array[count-1] = x;
}
template <typename T>
void MyStack<T>::pop(T x)
{
}
main.cpp:
#include <iostream>
#include "mystack.h"
using namespace std;
int main(int argc, char *argv[])
{
MyStack<int> s;
s.push(1);
return 0;
}
Possible Duplicate:
Undefined reference error for template method
Hello I have this code that is giving me this error:
undefined reference to `MyStack::push(int)' main.cpp
Why??
MyStack.h:
#ifndef STACK_H
#define STACK_H
template <typename T>
class MyStack
{
private:
T *stack_array;
int count;
public:
void push(T x);
void pop(T x);
void xd(){}
};
#endif /* STACK_H */
MyStack.cpp:
#include "mystack.h"
template <typename T>
void MyStack<T>::push(T x)
{
T *temp;
temp = new T[count];
for(int i=0; i<count; i++)
temp[i] = stack_array[i];
count++;
delete stack_array;
stack_array = new T[count];
for(int i=0; i<count-1; i++)
stack_array[i] = temp[i];
stack_array[count-1] = x;
}
template <typename T>
void MyStack<T>::pop(T x)
{
}
main.cpp:
#include <iostream>
#include "mystack.h"
using namespace std;
int main(int argc, char *argv[])
{
MyStack<int> s;
s.push(1);
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
类模板成员的定义必须位于同一文件中,但您已在不同的文件 (
MyStack.cpp
) 中定义它们。简单的解决方案是将以下行添加到您的
MyStack.h
文件末尾:我知道那是
.cpp
文件,但这将解决您的问题。也就是说,您的
MyStack.h
应该如下所示:如果您这样做,则
MyStack.cpp< 中不需要
#include "mystack.h"
/code> 不再了。你可以删除它。The definition of the members of the class template must be in the same file, but you've defined them in a different file (
MyStack.cpp
).The simple solution is that add the following line to your
MyStack.h
file at the end:I know that is
.cpp
file, but that will solve your problem.That is, your
MyStack.h
should look like this:If you do so, then
#include "mystack.h"
is not needed inMyStack.cpp
anymore. You can remove that.请参阅 C++ FAQ-35.12
See C++ FAQ-35.12
您必须将模板类声明和实现放在头文件中,因为编译器在编译时实例化模板时需要了解模板实现。尝试将
MyStack
的实现放在MyStack.h
中您可以找到更详细的解释这里。只需转到本文开头的“模板和多文件项目”即可。
You have to place your template class declaration and implementation inside header file because compiler needs to know about template implementation when instantiating template while compiling. Try to put implementation of
MyStack
insideMyStack.h
You can find more detailed explanation here. Just move to the "Templates and multiple-file projects" at the bootom of the article.