以下程序对我来说看起来还不错。但我无法编译它。
#include <iostream>
#include <vector>
using namespace std;
int main()
{
struct a
{
int i;
int j;
};
std::vector<a*> vecA;
a* pA = new a;
pA->i = 4;
pA->j = 9;
vecA.push_back(pA);
return 0;
}
它会产生以下错误。
struct_update.cc: In function ‘int main()’:
struct_update.cc:32:19: error: template argument for ‘template<class _Alloc> class std::allocator’ uses local type ‘main()::a*’
struct_update.cc:32:19: error: trying to instantiate ‘template<class _Alloc> class std::allocator’
struct_update.cc:32:19: error: template argument 2 is invalid
struct_update.cc:32:25: error: invalid type in declaration before ‘;’ token
struct_update.cc:39:10: error: request for member ‘push_back’ in ‘vecA’, which is of non-class type ‘int’
最佳答案
在新的 C++11 标准中不再如此,但当前的编译器还没有完全实现它。
局部类型不能是模板参数。将您的结构定义移至 main
之上,一切都会正常进行。
或者将您的编译器更新为支持 C++11 这一部分的编译器。
这是 C++03 第 14.3.1 节 ([temp.arg.type]
) 的限制,它在 C++11 中被删除:
A local type, a type with no linkage, an unnamed type or a type compounded from any of these types shall not be used as a template-argument for a template type-parameter.
关于c++ - 指向结构的指针 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8814146/