初始化:无法从'_Ty*';列出<;int,std::分配器<;节点<;T>&燃气轮机>;:节点* 我是C++新手。 我开始使用类模板创建容器列表,但是如果我在main中实例化类模板列表,则VS编译器会给我一个错误,如下所示: 名单l(5); 如果我删除main()中的这一行,代码就可以编译了。或者,如果在类列表之外定义类节点,则不会出现此错误。编译器在这一行发出错误代码: node_ptr head = (alloc.allocate(s));

初始化:无法从'_Ty*';列出<;int,std::分配器<;节点<;T>&燃气轮机>;:节点* 我是C++新手。 我开始使用类模板创建容器列表,但是如果我在main中实例化类模板列表,则VS编译器会给我一个错误,如下所示: 名单l(5); 如果我删除main()中的这一行,代码就可以编译了。或者,如果在类列表之外定义类节点,则不会出现此错误。编译器在这一行发出错误代码: node_ptr head = (alloc.allocate(s));,c++,class,templates,C++,Class,Templates,请帮忙。多谢各位 #include "pch.h" #include <iostream> #include <memory> using namespace std; template<class T> class Node; //forward declaration template< class T, typename Allocator = std::allocator<

请帮忙。多谢各位

    #include "pch.h"  
    #include <iostream>  
    #include <memory>  
    using namespace std;  
    template<class T> class Node; //forward declaration  
    template< class T, typename Allocator = std::allocator<Node<T>>>  
    class List  
    {  
        using data_ptr = T *;  
        using data_type = T;  
        class Node {  
          public:  
             T value;  
             Node* next;  
             Node() : value(data_type()), next(0) {}  
        };  
        using node = Node;  
        using node_ptr = Node*;  

        public:  
          List() : length(0), head(NULL), alloc(std::allocator<int>()) {}  
          explicit List(size_t s) : length(s), head(NULL), alloc(std::allocator<Node>())  
          {  
              node_ptr head = (alloc.allocate(s));  
           }  
          ~List() {};  

        //private:
        node_ptr head;
        size_t   length;
        Allocator  alloc;
    };
    int main()  
    {  
        List<int> l(5); //The compile error is gone if this line is removed
        system("pause");  
        return 0;  
    }  

#包括“pch.h”
#包括
#包括
使用名称空间std;
模板类节点//远期申报
模板
班级名单
{  
使用数据_ptr=T*;
使用数据_type=T;
类节点{
公众:
T值;
节点*下一步;
Node():值(数据类型()),下一个(0){
};  
使用node=node;
使用node_ptr=node*;
公众:
List():长度(0),头(NULL),alloc(std::allocator()){}
显式列表(大小):length(s)、head(NULL)、alloc(std::allocator())
{  
节点头=(分配分配);
}  
~List(){};
//私人:
节点头;
尺寸与长度;
分配程序alloc;
};
int main()
{  
List l(5);//如果删除这一行,编译错误将消失
系统(“暂停”);
返回0;
}  

第一个
节点
被定义为类模板:

template<class T> class Node; //forward declaration  
模板类节点//远期申报
根据以下内容默认分配程序:

std::allocator<Node<T>>
std::分配器
但是,稍后,节点被定义为列表的内部类,而不是模板。 这就是编译器抱怨的原因:Node*!=节点*

一种解决方案是将分配器默认为std::allocator,并使用rebind获取节点分配器:

using node_allocator = Allocator::template rebind_alloc<Node<T>>;
使用node\u allocator=allocator::template rebind\u alloc;

您的代码中还有其他错误/警告,例如:列表构造函数的init列表中的初始化顺序错误,或者您使用局部变量
head
对类成员
head
进行了阴影处理,谢谢!我很难格式化代码。我发布了代码,编译器给出了什么错误?