【发布时间】:2019-01-19 14:46:52
【问题描述】:
我是 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 下失败?我是不是做错了什么?
【问题讨论】:
标签: c++ visual-studio-2017 c++17