c++ - 模板问题

扫码查看

我有三个文件,我想编译并运行它们,但是我不断收到一些错误和警告。重新定义结构Node 。我对模板了解不多,但这对我来说似乎很对。而且,我花了很多时间试图找出问题所在。谢谢。

//mystack.h
#ifndef MYSTACK_H
#define MYSTACK_H

template <class T>
struct Node
{
    T info;
    T *next;
};

template <class T>
class MyStack
{
private:
    struct Node<T> *top;
public:

    void Push(T item);

    void Pop();

    int Top();

    void Print();
};

#endif




//mystack.cpp
#include <iostream>
#include "mystack.h"

template <class T>
struct Node
{
    T info;
    T* next;
};

template <class T>
class MyStack
{
private:
    struct Node<T>* top;

public:
    void Push(T item)
    {
        if(top == NULL)
        {
            top = new( struct Node<T> );
            top->info = item;
            top->next = NULL;
        } else
        {
            Node<T>* temp;
            temp = top;
            top = new( struct Node<T> );
            top->info = item;
            top->next = temp;
        }
    }

    void Pop()
    {
        if( top == NULL )
        {
        } else
        {
            Node<T>* temp;
            temp = top->next;
            delete top;
            top = temp;
        }
    }

    int Top()
    {
        return top;
    }

    void Print()
    {
        if(top != NULL)
        {
            Node<T>* temp;
            temp = top;
            while(temp != NULL)
            {
                std::cout << temp << std::endl;
                temp = temp->next;
            }
        }
    }
};

最佳答案

如果您设计的是类而不是模板,那么您正在做的事情将是错误的,因为您正在重新定义类型。

但是由于您正在编写模板,所以您早于此就犯了错误:您无法单独编译模板。

C ++编译模型的简要说明:

// Definition of Node
template<typename T>
struct Node {
    T info;
    T* next; // shouldn't that be a Node*?
};

// Definition of MyStack
template <typename T>
class MyStack
{
private:
    Node<T> *top;
public:

    // Declarations, but not definitions, of the Mystack function members.
    void Push(T item);
    void Pop();
    int Top();
    void Print();
};

// Example definition of MyStack::Push
template<typename T>
void
MyStack<T>::Push(T item)
{
    // as before
}


类型定义通常会出现在带有包含保护的标头中(如果要在不同的TU中重用)。保护措施在这里是因为每个TU定义最多只能出现一次。请勿手动重复类型定义(例如,像在源文件中那样)。这是应该的,这是错误的:没有人希望复制-粘贴错误。

函数成员定义通常出现在源文件中,除非它们是模板的成员。在后一种情况下,将它们放在标头中更为简单(它们也不必内联)。

您可以在SO,书籍或Internet上的其他地方了解编译模型的详细信息。搜索“模板定义”或“一个定义规则”(或ODR)会有所帮助。

关于c++ - 模板问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6567644/

10-14 16:45
查看更多