正在初始化:无法从'_Ty*'转换为 List<int,std::分配器<节点<T>>>:节点*
Initializing: cannot convert from '_Ty*' to List<int, std::allocator<Node<T>>>:Node*
我是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
。
相关文章:
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 呼叫运营商<<临时
- 如何防止clang格式在流运算符调用之间添加换行符<<
- <<操作员在下面的行中工作
- EASTL矢量<向量<int>>连续的
- C - 创建矢量&lt; vector&lt; double&gt;&gt;矩阵具有分配而不是inizializ
- 为什么将此对向量&lt; map&lt; int,int&gt;&gt;中的地图进行更新.失败
- C :对矢量进行排序&lt; struct&gt;(结构有2个整数)基于结构的整数之一
- 明确的专业化“ CheckIntmap&lt;&gt;”实例化
- 什么是模板&lt;&gt;inline bla bla
- 编辑C Qlist&lt; object*&gt; gt;QML代码和一些QML警告中的模型
- eigen :: llt&lt;eigen :: matrixxd&gt;具有不完整的类型
- 错误,包括&lt; ctype&gt;在原子上使用C 11
- std::vector<;uint8_t>;当C++11/14启用时,手动复制而不是调用memcpy
- 如何加入向量&lt; int&gt;到C 中的单个INT
- 是std :: set&lt; std :: future&gt;不可能存在
- 是numeric_limits&lt; int&gt; :: is_modulo从逻辑上矛盾
- opencv 2.4.7在iOS错误背景_segm.hpp #include&lt; list&gt;未找到
- 在修改列表后,std :: list&lt; t&gt; :: end()的值是否会更改
- ///<评论></评论>在Visual Studio中