簡體   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