gpt4 book ai didi

c++ - VS2013 - 静态常量已经定义

转载 作者:可可西里 更新时间:2023-11-01 17:56:44 25 4
gpt4 key购买 nike

我有以下代码(已简化),它在 gcc 中编译良好,但在 VS 中出错:

// main.cpp
#include "test.h"
int main() {
return 0;
}

// test.h
#pragma once
class Test {
static const int TEST = 3;
};

// test.cpp
#include "test.h"
const int Test::TEST;

错误:

main.obj : error LNK2005: "private: static int const Test::TEST" (?TEST@Test@@0HB) already defined in test.obj

这是 VS 错误还是 gcc 错误地允许我明确定义静态常量成员?

更新:C++ Standard 中找到了这个(9.4.2.3):

If a non-volatile const static data member is of integral or enumeration type, its declaration in the class definition can specify a brace-or-equal-initializer in which every initializer-clause that is an assignment-expression is a constant expression (5.20). A static data member of literal type can be declared in the class definition with the constexpr specifier; if so, its declaration shall specify a brace-or-equal-initializer in which every initializer-clause that is an assignment-expression is a constant expression. [ Note: In both these cases, the member may appear in constant expressions. — end note ] The member shall still be defined in a namespace scope if it is odr-used (3.2) in the program and the namespace scope definition shall not contain an initializer.

更新 #2: 发现一个 bug report ,它声称它已在下一个主要版本中修复。

最佳答案

正如您所说,它是一个 MSVC bug .使用默认项目选项,代码可以在 Visual Studio 2015 RC 中完美编译和运行。

enter image description here

编译器认为“static const int TEST = 3;”和“const int 测试::测试;”是同一变量的两种不同定义。要在您的版本中解决此问题,您可以尝试在 .cpp 文件中设置静态变量值:

// test.h
#pragma once
class Test {
static const int TEST;
};

// test.cpp
#include "test.h"
const int Test::TEST = 3;

关于c++ - VS2013 - 静态常量已经定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31074546/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com