0

在一些几年前可以编译的代码中,现在我有错误,这里是一行:

std::vector<aRequest*> requests(aCount, NULL);

似乎有人想要初始化一个大小为 aCount ( type long) 的向量,并且每个指针都想要初始化为 null。查看 stl 文档,在这种情况下,有人正在尝试使用填充构造函数:

explicit vector (size_type n, const value_type& val = value_type(),
                 const allocator_type& alloc = allocator_type());

Constructs a container with n elements. Each element is a copy of val

我的编译器给了我错误:

In file included from /usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/vector:65,
                 from server/ServerCreator.h:29,
                 from server/ServerApplication.h:31,
                 from server/ServerApplication.cpp:24:
/usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/bits/stl_vector.h: In member function âvoid std::vector<_Tp, _Alloc>::_M_initialize_dispatch(_Integer, _Integer, std::__true_type) [with _Integ er = long int, _Tp = ToolboxServer::aRequest*, _Alloc = std::allocator<ToolboxServer::aRequest*>]:
/usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/bits/stl_vector.h:303:   instantiated from âstd::vector<_Tp, _Alloc>::vector(_InputIterator, _InputIterator, const _Alloc&) [with _InputIterator = long int, _Tp = ToolboxServer::aRequest*, _Alloc = std::allocator<ToolboxServer::aRequest*>]
server/ServerApplication.cpp:1056:   instantiated from here
/usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/bits/stl_vector.h:991: error: invalid conversion from long int to ToolboxServer::aRequest*
/usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/bits/stl_vector.h:991: error:   initializing argument 2 of âvoid std::vector<_Tp, _Alloc>::_M_fill_initialize(size_t, const _Tp&) [with _Tp = ToolboxServer::aRequest*, _Alloc = std::allocator<ToolboxServer::aRequest*>]
make: *** [bin/Debian/x86/GCC4/2.6/Release/ServerApplication.o] Error 1

所以,要修复它,我应该删除NULL,并使用默认向量构造函数,还是有任何其他选项,将该向量中的每个指针初始化为NULL

问候J。

4

1 回答 1

1

问题在于NULL0没有被解释为指针。您需要将其转换为aRequest*.

std::vector<aRequest*> requests(aCount, static_cast<aRequest*>(NULL));

您也可以nullptr在 C++11 中使用,或者按照评论者的建议根本不使用。

std::vector<aRequest*> requests(aCount, nullptr);

std::vector<aRequest*> requests(aCount);

于 2013-08-19T09:11:02.837 回答