【问题标题】:Vector of pointers to struct指向结构的指针向量
【发布时间】:2012-02-07 12:09:12
【问题描述】:

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

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

【问题讨论】:

  • 对我来说编译得很好...(Visual Studio 2010 SP1)
  • @honk 上面的代码不适用于 g++(最新版本可用于 ubuntu 11.10 至今)

标签: c++ pointers vector struct


【解决方案1】:

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

本地类型不能是模板参数。将您的结构定义移到main 上方,一切正常。

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

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

本地类型、无链接类型、未命名类型或由这些类型中的任何一种复合的类型不应用作模板类型参数的模板参数

【讨论】:

    【解决方案2】:

    将结构定义移出主函数。

       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);
    

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

    本地类型、无链接类型、未命名类型或由这些类型中的任何一种复合而成的类型不得用作模板类型参数的模板参数。

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

    【讨论】:

      猜你喜欢
      • 2018-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-04
      • 1970-01-01
      • 2011-08-04
      相关资源
      最近更新 更多