我最近开始使用“警告级别 4”,并在使用 C++ 编码时将警告视为错误。我想要有关以下代码段的一些更深入的信息:
struct Foo
{
Foo(int size)
//:size{ size } // <- More on this later.
{
this->size = size;
}
void func(int size)
{
this->size = size;
}
int size;
};
int main()
{
Foo a{ 1 };
a.func(2);
}
因此,我从 Visual Studio 2019 收到以下警告/错误:
Error: C2220 - Warning treated as error - no 'object' file generated.
Warning: C4458 - Declaration of 'size' hides class member.
该警告表明 size
成员被方法的参数隐藏,该方法的参数也名为 size
。输出表明错误不是来自构造函数,而是来自 func
方法。我发现这令人困惑,因为构造函数似乎没有这个问题(实际上,删除 func
允许代码片段编译)。
降低警告级别允许应用程序编译,并且它似乎按预期工作。使用初始化列表而不是构造函数的主体(参见注释行)似乎也可行,但我猜这是由于初始化列表语义所致。
我理解错误说func
的size
参数名与Foo
的同名成员冲突,但是应该this
关键字解决了这个困惑吗?这只是微软的编译器过于严格了吗?
最佳答案
but shouldn't the
this
keyword fix that confusion?
这并不是编译器对 this->size
与 size
的不同感到困惑。即使删除该行,您也很可能会收到警告。编译器警告您函数的参数名称隐藏了成员名称。
关于C++:即使使用 "this"关键字,参数声明也会隐藏类成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55411020/