指向向量的结构

Dil*_*war 5 c++ struct pointers vector

以下程序看起来对我很好.但我无法编译.

#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;
}
Run Code Online (Sandbox Code Playgroud)

它会产生以下错误.

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’
Run Code Online (Sandbox Code Playgroud)

Ben*_*igt 12

在新的C++ 11标准中,这不再是真的,但是当前的编译器还没有完全实现它.

本地类型不能是模板参数.将结构定义移到上面main,一切都会起作用.

或者将编译器更新为支持C++ 11的这一部分的编译器.

这是C++ 03第14.3.1节([temp.arg.type])中的限制,它在C++ 11中被删除:

本地型,没有键,无名类型或任何这些类型的配混一个类型的类型不应被用作模板参数为模板类型参数.


par*_*mar 6

将结构定义移出main函数.

   struct a
    {
        int i;
        int j;
    };

int main()
{

    std::vector<a*> vecA;

    a* pA = new a;

    pA->i = 4;
    pA->j = 9;

    vecA.push_back(pA);
Run Code Online (Sandbox Code Playgroud)

在C++ 03中你不能这样做

本地类型,没有链接的类型,未命名的类型或从这些类型中的任何类型复合的类型不应该用作模板类型参数的模板参数.

在C++ 11中我认为你可以按照标准.即使我的Visual Studio 11编译器拒绝允许它