我使用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);
,并在此之后建立良好状态。在我使用static
和sizeof(memberArray)
在sizeof(memberArray[0])
函数中尝试执行类似操作的另一个实例中,此问题更加复杂。
我认为这是符合标准的,因为g++
喜欢它,而且在微软编译器松散标准之前我已经听过,接受一种伪c / c ++语言。< / p>
sizeof(myVariable)
,因为它更易于维护(如果myVariable
的类型发生变化,则sizeof
无需进行任何更改)。在编译时,编译器应该知道(如g ++那样)myVal
的类型,而不关心它是否是类的成员。修改 我也尝试过:
static const size_t staticLength = sizeof(this->myVal);
和
static const size_t staticLength = sizeof(staticTest::myVal);
都失败了。
答案 0 :(得分:1)
这适用于我的Visual Studio编译器:
static const size_t staticLength = sizeof(decltype(myVal));
据我所知,这应该适应myVal类型的任何变化。
如果您不必在课程定义中对其进行初始化,请不要在课程内部初始化并具有:
const size_t staticTest::staticLength = sizeof staticTest::myVal;
在.cpp文件中