【问题标题】:C++ Template error [duplicate]C ++模板错误[重复]
【发布时间】:2011-04-27 08:57:08
【问题描述】:

可能重复:
Undefined reference error for template method

你好,我有这段代码给我这个错误:

对 `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;
}

【问题讨论】:

  • 顺便说一句,在构造函数中使用它之前,您还需要初始化计数变量。
  • 谢谢!!!我确实注意到需要初始化,但我真的很想解决这个问题,因为这让我很紧张,哈哈。

标签: c++ templates


【解决方案1】:

类模板成员的定义必须在同一个文件中,但您已在不同的文件中定义它们 (MyStack.cpp)。

简单的解决方案是将以下行添加到您的 MyStack.h 文件末尾:

#include "MyStack.cpp" // at the end of the file

我知道那是.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(){}
};

#include "MyStack.cpp" // at the end of the file

#endif /* STACK_H */

如果你这样做了,那么 #include "mystack.h" 就不再需要在 MyStack.cpp 中了。您可以删除它。

【讨论】:

  • 谢谢!我只是把所有的东西都写在 .h 文件里了,哈哈!
【解决方案2】:

【讨论】:

    【解决方案3】:

    您必须将模板类声明和实现放在头文件中,因为编译器在编译时实例化模板时需要了解模板实现。尝试将MyStack 的实现放在MyStack.h

    你可以找到更详细的解释here。只需转到文章开头的“模板和多文件项目”即可。

    【讨论】:

      猜你喜欢
      • 2010-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-11
      • 2016-01-20
      • 1970-01-01
      相关资源
      最近更新 更多