正在初始化:无法从'_Ty*'转换为 List<int,std::分配器<节点<T>>>:节点*

Initializing: cannot convert from '_Ty*' to List<int, std::allocator<Node<T>>>:Node*

本文关键字:lt gt 节点 int std 分配器 List Ty 初始化 转换      更新时间:2023-10-16

我是C++新手。 我开始使用类模板创建一个容器列表,但是如果我像这样在 main 中实例化类模板 List,VS 编译器会给我一个错误: 列表 l(5(; 如果我在 main(( 中删除这一行,代码编译正常。或者,如果我在类列表之外定义类节点,则没有此错误。编译器在此行代码处发出错误:

node_ptr head = (alloc.allocate(s));

请帮忙。谢谢!

#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;  
}  

第一个Node被定义为类模板:

template<class T> class Node; //forward declaration  

分配器默认为:

std::allocator<Node<T>>

但是,稍后,Node 被定义为 List 的内部类,而不是模板。 这就是编译器抱怨的原因:节点* != 节点*

一种解决方案是将分配器默认为 std::分配器,并使用重新绑定来获取节点分配器:

using node_allocator = Allocator::template rebind_alloc<Node<T>>;

代码中还有其他错误/警告,例如:List ctor 的初始化列表中的初始化顺序错误,或者您使用局部变量head隐藏类成员head