C ++在类成员映射其父类的成员时生成警告? [英] C++ generate a warning when a class member shadow a class member of its parent?
问题描述
是否有一种方法在派生类成员变量名称遮蔽其父类之一时生成警告,例如
Is there a way to generate a warning when a derived class member variable name shadows one of its parents class, e.g
class Mother
{
public:
Mother() : i(0) {}
virtual ~Mother() {}
protected:
int i;
};
class Child : public Mother
{
public:
Child() : Mother(), i(0) {}
virtual ~Child() {}
protected:
int i; /* NOK Expecting warning : declaration of 'int Child::i' shadows 'int Mother::i' */
};
使用 -Wshadow $ c $编译时,以上代码不会产生警告c> with g ++。
Above code generates no warning when compiled with -Wshadow
with g++.
推荐答案
我的代码如下所示,它显示了影子警告的必要性。 b
$ b
I actually saw code as follows which shows the necessity of the shadow warnings.
int val = 0;
if (flag == aval)
int val = firstval;
else if (flag == bval)
int val = secondval;
else if
.
.
.
switch (val)
{
// put cases here
}
我也看到了影子警告,其中内部变量是本地的,对外部变量没有影响,并且阴影变量不应该影响被引用。实际上,更改名称以防止发出警告更容易。
I have also seen shadow warnings where the inside variable was meant to be local, have no effect on the outside variable, and the shadowed variable was not supposed to be referenced. Actually, it was easier to just change the name to prevent the warning.
这篇关于C ++在类成员映射其父类的成员时生成警告?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!