【问题标题】:Can you use the sizeof one member when declaring another member?声明另一个成员时可以使用一个成员的大小吗?
【发布时间】:2012-09-20 08:26:44
【问题描述】:

这是合法的 C++ 吗?

struct foo
{
  int a[100];
  int b[sizeof(a) / sizeof(a[0])];
};

GCC 4.6 接受它,但 MSVC 2012 不接受。对我来说似乎应该没问题,但是一点谷歌搜索没有帮助,我不知道在哪里查看标准。

MSVC 2012 给出以下输出:

error C2327: 'foo::a' : is not a type name, static, or enumerator
error C2065: 'a' : undeclared identifier
error C2070: ''unknown-type'': illegal sizeof operand
warning C4200: nonstandard extension used : zero-sized array in struct/union

【问题讨论】:

标签: c++


【解决方案1】:

这在 C++03 中是非法的,因为这些成员是非静态数据成员。

从 C++11 开始,这是合法的,因为在未计算的操作数中,您可以在没有相应对象的情况下使用非静态数据成员。

【讨论】:

    【解决方案2】:

    试试这个:这是 MSVC 2010 和 MSVC 2012 的解决方法

    struct Aoo
    {
        typedef int ArrayType;
        ArrayType a[100];
    };
    
    struct foo : public Aoo
    {   
        enum {bSize = sizeof(Aoo) / sizeof(Aoo::ArrayType)};
        int b[bSize];
    };
    

    【讨论】:

      猜你喜欢
      • 2011-05-22
      • 1970-01-01
      • 2011-11-23
      • 2021-10-08
      • 2017-06-28
      • 1970-01-01
      • 2020-11-25
      • 1970-01-01
      相关资源
      最近更新 更多