gpt4 book ai didi

c++ - 为什么编译器会警告隐藏初始化列表中的成员?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:10:56 32 4
gpt4 key购买 nike

采用与正在初始化的数据成员具有相同标识符的构造函数参数。如果两者在初始化列表中使用,则认为是安全的,并且不会发生“遮蔽”。

但是,举个例子:

struct A{
A(int a, int b);
int a, b;
};

A::A(int a, int b)
: a(a)
, b(b)
{}

int main(){}

使用 g++ 时出现的警告:

g++ -Wshadow --std=c++1z -o main main.cpp 
main.cpp: In constructor ‘A::A(int, int)’:
main.cpp:8:18: warning: declaration of ‘b’ shadows a member of ‘A’ [-Wshadow]
A::A(int a, int b)
^
main.cpp:4:10: note: shadowed declaration is here
int a, b;
^
main.cpp:8:18: warning: declaration of ‘a’ shadows a member of ‘A’ [-Wshadow]
A::A(int a, int b)
^
main.cpp:4:7: note: shadowed declaration is here
int a, b;

用 clang 看到的警告:

clang++ -Wshadow --std=c++1z -o main t.cpp
main.cpp:8:10: warning: declaration shadows a field of 'A' [-Wshadow]
A::A(int a, int b)
^
main.cpp:4:7: note: previous declaration is here
int a, b;
^
main.cpp:8:17: warning: declaration shadows a field of 'A' [-Wshadow]
A::A(int a, int b)
^
main.cpp:4:10: note: previous declaration is here
int a, b;

我没有对构造函数主体中的数据成员执行任何操作——那么为什么我会收到这些警告?

我想启用警告标志以捕获合法的事故,但这些特殊情况会导致过多的错误噪音。这些警告是否有效?

最佳答案

虽然您现在没有做任何阴影可能会伤害您的事情,但您正在为一些维护问题做好准备。

如果维护者 Joe 出现并且需要像这样进行更改:

A::A(int a, int b)
: a(a)
, b(b)
{
storeReference(a);
}

糟糕!他只是存储了对参数而不是数据成员的引用。

编译器并没有告诉你你本身做错了什么,它只是告诉你你可能想要更改你的名字,这样你将来就不会遇到问题。

我个人建议选择一种命名约定来消除歧义并坚持使用。就个人而言,我喜欢将m_放在成员数据的前面,但其他人更喜欢在成员数据或构造函数参数的前面加上后缀_

关于c++ - 为什么编译器会警告隐藏初始化列表中的成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34895661/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com