无法使用sizeof(成员变量)在Visual Studio

时间:2018-03-14 23:37:23

标签: c++ visual-studio-2013

我使用g ++ 5.3.1在Fedora 23盒子上开发了一个库,并使用mingw在Windows机器上成功构建了这个库(如果需要,我可以在这里获取版本)。我把这个代码交给了今天有兴趣使用它的同事。他尝试在Visual Studio 2013(他选择的IDE)中编译它,然后它爆炸了。下面我已经创建了问题的MCVE:

#include "stdafx.h"  // include this while in Visual Studio
#include <iostream>  // include when compiling with g++

class staticTest
{
public:
  staticTest() { };
  ~staticTest() { };

  unsigned myVal;

private:
  static const size_t staticLength = sizeof(myVal);  // errors in VS2013, compiles fine with g++ and mingw
  const size_t length_ = sizeof(myVal);  // compiles fine for all
};

使用g++ -Wall -Wextra -std=c++11 -c staticTest.cpp进行编译时没有错误或警告。但是,在Visual Studio 2013中,我收到有关staticLength分配行的以下3个错误:

statictest.cpp(12): error C2327: 'staticTest::myVal' : is not a type name, static, or enumerator
statictest.cpp(12): error C2065: 'myVal' : undeclared identifier
statictest.cpp(12): error C2070: 'unknown-type': illegal sizeof operand

我知道错误基本上是什么,它没有在static上下文中看到成员变量,因此无法将sizeof运算符应用于它。通过咬紧牙关,我批准将所有这些实例更改为static const size_t staticLength = sizeof(unsigned);,并在此之后建立良好状态。在我使用staticsizeof(memberArray)sizeof(memberArray[0])函数中尝试执行类似操作的另一个实例中,此问题更加复杂。

我认为这是符合标准的,因为g++喜欢它,而且在微软编译器松散标准之前我已经听过,接受一种伪c / c ++语言。< / p>

  1. 这是不好的编码风格?我总是喜欢使用sizeof(myVariable),因为它更易于维护(如果myVariable的类型发生变化,则sizeof无需进行任何更改)。在编译时,编译器应该知道(如g ++那样)myVal的类型,而不关心它是否是类的成员。
  2. 如果有人知道在Visual Studio 2013中解决此问题,或者在Visual Studio的更高版本中修复此问题,是否有机会?对我来说真正的踢球者是Windows mingw编译得很好,但是我的同事不会从VS那里掏空,所以我在这里修改我的代码,使其不那么易于维护,只是为了遵守一个不稳定的IDE的想法/编译器。哦,他的最终可执行文件将为Linux构建,并在与我相同的盒子上运行,因此在VS中构建它甚至不是必需的或者是一个要求...... [生气/呕吐表情符号]
  3. 修改 我也尝试过:

    static const size_t staticLength = sizeof(this->myVal);
    

    static const size_t staticLength = sizeof(staticTest::myVal);
    

    都失败了。

1 个答案:

答案 0 :(得分:1)

这适用于我的Visual Studio编译器:

static const size_t staticLength = sizeof(decltype(myVal)); 

据我所知,这应该适应myVal类型的任何变化。

如果您不必在课程定义中对其进行初始化,请不要在课程内部初始化并具有:

const size_t staticTest::staticLength = sizeof staticTest::myVal;

在.cpp文件中