c++ - 指向结构的指针 vector

标签 c++ pointers vector struct

以下程序对我来说看起来还不错。但我无法编译它。

#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/

相关文章:

c - C 中赋值中的不兼容类型

c++ - C++程序中的 vector 错误

c++ - 无法访问多态性子类的成员

c++ - 代码守卫失败,模板来自字符串文字

c++ - 从 push_front 操作获取常规 MPL 列表

c++ - C++ 中的指针 : How large should an object be to need use of a pointer?

c - 带有结构体指针数组的 strcpy() 的段错误

C++ - 读取 1000 个 float 并通过仅保留最低的 10 个数字将它们插入大小为 10 的 vector 中

c++ - operator [] 在 vector 类上重载

java - 关于extern "C"的C++到Java的转换问题