如何让 VS2015 正确地拒绝在 class 声明中使用 class 前缀?

How do I get VS2015 to rightly reject use of a class prefix in the class declaration?

我最近将我的 cpp 文件中的一个 C++ 成员函数复制并粘贴到 header 中,但忘记删除前缀。所以,在 cpp 文件中,我有类似的东西:

int MyClass::Return42() const { return 42; }

并且,在我的 header 中:

class MyClass {
public:
    int MyClass::Return42() const;
};

现在我确定我以前做过,编译器抱怨说不允许,要求删除 class 前缀header。事实上,g++ 5.4.0 在 Linux 下抱怨它,无论我针对哪个 ISO 标准(11 到 17),使用 单个 文件(尽管 -fpermissive会将其变成警告而不是错误):

#include <iostream>

class MyClass {
public:
    int MyClass::Return42() const;
};

int MyClass::Return42() const { return 42; }

int main() {
    MyClass x;
    std::cout << x.Return42() << '\n';
}

但我发现我全新安装的 VsPro15 似乎允许这样做。

如何让 Visual Studio 拒绝这个无效代码,因为我希望我的代码可以跨不同平台移植?


我知道 suggested solutions 涉及 /permissive-/Ze

对于第一个,即使使用 VS2k15 更新 3,在 Project properties | C/C++ | Command Line | Aditional Options 字段中输入 /permissive-,也会导致:

2>cl : Command line warning D9002: ignoring unknown option '/permissive-'

第二个,我看到:

2>cl : Command line warning D9035: option 'Ze' has been deprecated and will be removed in a future release

但它还是会编译错误代码。

所以我认为这两者都不是可行的解决方案。

在以下文章中查找 C4596:

https://blogs.msdn.microsoft.com/vcblog/2016/11/16/permissive-switch/

//Use of qualified names in member declarations


struct A {
    void A::f() { } // error C4596: illegal qualified name in member declaration
                    // remove redundant 'A::' to fix
};

据我所知,你 不会 无法让 VS2015 对此发出警告。 This document 声明您需要 /permissive- 开关才能获得此特定警告。它还声明它应该包含在 VS2015 中。也许这是一个编译器错误?

然而在 VS2017 中,你可以使用 /permissive- 开关,使编译器更符合标准(这也是一个提示,它不符合标准,但我找不到合适的地方在标准中 -- 也许有人可以填写),请参阅 here。 有了这个你会得到警告:

error C4596: 'Return42': illegal qualified name in member declaration

您想要的警告也可以使用 /we4596 触发,以仅启用此警告,而不是所有来自更标准的符合编译器的警告。

当我正确理解文档时,在 VS2015 中你可以使用 /Ze 开关(与 /permissive- 相反),但是,当我正确使用 compiler-explorer 时,这仍然没有警告,见 here. The /Ze switch is also discussed in this SO question.

编辑:

我发现 this 那里说编译器版本 19.00.24215.1 中引入了 警告 C4596。编译器资源管理器当前具有较旧的编译器(即 19.00.24210),因此这可能是它无法正常工作的原因。

警告级别documentation

/wennnn: Treats the compiler warning that is specified by nnnn as an error.

所以根据上面@p-i 的评论,对于警告 C4596,添加参数 /we4596 就可以达到 then.

<source>(5): error C4596: 'Return42': illegal qualified name in member declaration
Compiler returned: 2

虽然添加 /w14596 仅作为警告发出,但如果您 prefered.

<source>(5): warning C4596: 'Return42': illegal qualified name in member declaration
Compiler returned: 0

正如下面@p-i 的评论,这仅适用于 VS2017++