C++ 错误 : class template has already been defined

标签 c++ templates

我在 Visual Studio 2010 Pro 中收到此错误:“错误 C2953:‘list_1::Node’:类模板已定义”

这是出现错误的我的 Node.cpp 类列表(在第 24 行,代码的最后一行。)

#include "Node.h"

namespace list_1
{
    template <typename T>
    struct Node
    {
        //Constructor
        Node<T>(T D)
        {
            data = d;
            next = NULL;        
        }
    }
;}

和 Node.H 文件:

#pragma once

namespace list_1
{
    template <typename T>
    struct Node
    {
        T data;
        Node<T> *next;

        // Constructor
        // Postcondition: 
        Node<T> (T d);
    };
}

我已经看了here ,这对我没有帮助,因为我已经使用过一次#pragma,并且在列表头文件中我有#ifndef LIST_H 和#define LIST_H。这question不适合我的需要和这 answer 中的所有内容似乎与我已经拥有的模板位有关。

如果我尝试将其设为 struct Node,我会收到错误消息“error C2753: 'list_1::Node' : partial specialization cannot match argument list for primary template”

所以我不知道该怎么做。请帮忙。

最佳答案

对于一个普通的(非模板)类,你会做这样的事情:

//whatever.h
namespace Y 
    class X {
    public:
        X();
    };
}

然后在 cpp 文件中,你会有类似这样的内容:

namespace Y { 
    X::X() { /* ... */ }
}

然而,对于模板,您通常需要将实现放在编译器可以在任何将要使用它的地方看到它的地方,这通常意味着也将它放在 header 中。既然如此,相当多的人只是将定义写成类定义中的内联定义:

namespace Y { 
    template <class T>
    class X {
    public:
        X(T d) { /* ... */ }
    };
}

如果需要,您可以在类定义之外定义函数,但由于它们无论如何都将成为 header ,所以这并不能真正完成很多事情(至少在典型情况下)。

关于C++ 错误 : class template has already been defined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14544771/

相关文章:

javascript - 如何通过 django 中基于模板函数的 View 更改 Django 模型字段的值

php - 结合 PHP 和 HTML 的首选方式?

html - 完全控制 TYPO3 的 HTML 输出

c++ - throw() (即 __declspec(nothrow)) 是否在 Visual C++ 中提供了真正的好处?

c# - 将 C++ 函数转换为 C#(字符串问题)

c++ - 是否有像 eclipse cdt 这样的轻型 linux c++ IDE+Visual 调试器?

php - 如何在网站中包含虚拟键盘(数字键盘)?

c++ - 使用 boost 几何缓冲区缩放多边形时的冗余顶点

c++ - 使用 QRegExp 替换 QString 中的单词

c++ - 创建一个成员数量可变的类型