使用 g++ 编译 C++ 时,“隐藏构造函数”警告是什么意思?

2024-01-03

使用以下代码:

#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 编译时收到警告:

main.cpp:15:20: warning: ‘void my_struct()’ hides constructor for ‘struct my_struct’

如果 void my_struct 函数实际上替换了 my_struct::my_struct 函数,我会接受该警告。但事实似乎并非如此。如果我运行该程序,我会得到:

constructor
1-2

知道这个警告是什么意思吗?这很烦人,尤其是当我将 C 头文件包含到 C++ 代码中时


警告指出,my_struct()函数的名称与my_struct结构。这意味着你将无法写:

my_struct s;         // Error.

因为编译器会认为您正在使用函数作为类型。但是,正如您可能意识到的那样,您仍然可以使用以下方法实例化您的结构struct关键词:

struct my_struct s;  // Valid.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 g++ 编译 C++ 时,“隐藏构造函数”警告是什么意思? 的相关文章

随机推荐