当使用g ++编译C ++时,“隐藏构造函数”警告是什么意思? [英] What does the 'hides constructor for' warning mean when compiling C++ with g++?
问题描述
使用以下代码:
#include <stdio.h>
struct my_struct {
int a;
int b;
my_struct();
};
my_struct::my_struct(void)
{
printf("constructor\n");
}
void my_struct(void)
{
printf("standard function\n");
}
int main (int argc, char *argv[])
{
struct my_struct s;
s.a = 1;
s.b = 2;
printf("%d-%d\n", s.a, s.b);
return 0;
}
我使用g ++ -Wshadow main.cpp编译警告:
I get a warning compiling with g++ -Wshadow main.cpp:
main.cpp:15:20: warning: ‘void my_struct()’ hides constructor for ‘struct my_struct’
如果void my_struct函数实际上替换了my_struct :: my_struct,那么我会对该警告确定。但它似乎并不是这样的。如果我运行程序,我得到:
I would be ok with that warning if the void my_struct function actually replaced the my_struct::my_struct one. But it does not appears to be the case. If I run the program, I get:
constructor
1-2
任何想法这个警告是什么意思?特别是当我把C头文件包含到C ++代码中时,这很烦人。
Any idea what this warning mean ? It is quite annoying especially when I include C headers into C++ code
推荐答案
警告指出, my_struct()
函数与 my_struct
结构具有相同的名称。这意味着你将无法写下:
The warning points out that the my_struct()
function has the same name as the my_struct
structure. It means you will be unable to write:
my_struct s; // Error.
因为编译器会认为你使用函数作为类型。但是,您可能已经意识到,您仍然可以使用 struct
关键字实例化您的结构:
Because the compiler will think that you're using a function as a type. However, as you probably realized, you can still instantiate your structure with the struct
keyword:
struct my_struct s; // Valid.
这篇关于当使用g ++编译C ++时,“隐藏构造函数”警告是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!