繁体   English   中英

msvc内联静态成员变量重新定义

[英]msvc inline static member variable redefinition

我是C ++ 17的新手。 考虑以下代码:

// ---------------
// in MyClass.hpp
// ---------------
#pragma once

class MyClass {
public:
    static const int A;
};

inline const int MyClass::A = 100;

// ---------------
// in test.cpp
// ---------------
#include <stdio.h>
#include "MyClass.hpp"

void test() {
    printf("test: %p\n", &MyClass::A);
}

// ---------------
// in main.cpp
// ---------------
#include <stdio.h>
#include "MyClass.hpp"

extern void test();

int main() {
    printf("main: %p\n", &MyClass::A);
    test();
}

使用MinGW-W64 g ++ 8.1.0编译时

g++ -std=c++17 main.cpp test.cpp -o test.exe

输出是

main: 00000000004044B0
test: 00000000004044B0

它按预期工作。

但是,在MSVC 2017中

cl /std:c++17 main.cpp test.cpp

我收到一个编译器错误,说重新定义了“ public:static int const MyClass :: A”。 (很抱歉,编译器输出包含中文字符。不宜直接在此处发布。)

为什么代码可以在g ++下运行,但在MSVC中失败? 我做错什么了吗?

我可以确认Clang接受了您的代码而没有任何警告。

我担心的是cppreference显示以下注释:

内联说明符不能重新声明在转换单元中已定义为非内联的函数或变量(自C ++ 17起)。

我无法真正确定C ++标准中该注释的真正原因。 但是由于cppreference通常在其警告中是正确的,因此我认为这是MSVC在您的代码上造成阻塞的原因。 它可能会期望:

// ---------------
// in MyClass.hpp
// ---------------
#pragma once

class MyClass {
public:
    static const int A = 100;
};

为了避免之前的非内联声明和内联定义。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM