【问题标题】:Why does struct have two variable names in C/C++为什么struct在C/C++中有两个变量名
【发布时间】:2014-04-01 00:44:06
【问题描述】:

在下面的代码中,为什么结构有两个变量名?

#include <sys/resource.h>

int main (int argc, char **argv)
{
    const rlim_t kStackSize = 64L * 1024L * 1024L;

    struct rlimit rl;    //HERE

    int result = getrlimit(RLIMIT_STACK, &rl);


    return 0;
}

【问题讨论】:

  • 它有一个变量名:rl。如果是 C++,则不需要 struct,如果是 C,则可以更改类型使其不再需要。

标签: c++ c struct


【解决方案1】:

在 C 中,结构和它的标签一起是一个名称,除非它是 typedefed。

在 C++ 中,您可以省略 struct 关键字。

【讨论】:

  • 啊,所以 rlimit 是 struct 的“类型”?
  • @user997112 在 C 中,struct rlimit 是一个类型,rlimit 单独只是一个结构标签。
【解决方案2】:

如果这是 C,struct 只是告诉 C 它位于不同的命名空间中。

见:understanding C namespaces

如果这是 C++,则不需要 struct

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-07
    • 1970-01-01
    • 2022-12-03
    • 2021-03-18
    • 2021-03-22
    相关资源
    最近更新 更多