【问题标题】:Confused about how struct works in this piece of code对 struct 在这段代码中的工作方式感到困惑
【发布时间】:2015-02-23 15:47:59
【问题描述】:

我正在查看我将要使用的代码here

#include <sys/stat.h>

struct stat sb;

if (stat(pathname, &sb) == 0 && S_ISDIR(sb.st_mode))
{
    ...it is a directory...
}

我想如果我要使用它,我可能应该了解它的作用。我的问题是关于这条线

struct stat sb;

这是什么意思?我知道struct,就像声明它一样

struct node { int val; node * next; }

所以我很困惑为什么在结构声明之后有 2 个标记。

【问题讨论】:

  • 它创建了一个struct stat的实例。
  • @RSahu 那么为什么不只是stat sb 呢?为什么是struct
  • 虽然在这种情况下,C 和 C++ 的一切都应该是一样的,但你应该真正决定要保留两个标签中的哪一个!
  • C 中编程时,您必须使用struct stat sb;。只有在使用typedef struct stat stat; 创建了typedef 时,您才能使用stat sb;

标签: c++ c struct stat


【解决方案1】:

在 C 中,结构不会自动成为类型名称,因此您必须使用 struct foo 来引用结构名称。同样,您需要使用enum barunion baz。人们经常使用typedef 来避免在声明实例时输入struct

在 C++ 中,该关键字是可选的,因为结构、枚举和联合(加上类)都是类型,但您仍然可以编写 class std::string s = "abc";。关于stat,既有结构也有同名的函数,为了消除两者之间的歧义,在引用结构时需要写struct stat

【讨论】:

    【解决方案2】:

    这个

    struct node { int val; node * next; }
    

    你可以称之为“struct stat”类型的定义 这个

    struct stat sb;
    

    只需创建该类型的结构(已在其他地方定义) 例如在 stat.h 中;-)

    【讨论】:

    • “创建一个结构”不够接近。这是一个struct stat类型的变量初始化。
    猜你喜欢
    • 2012-10-05
    • 1970-01-01
    • 2012-08-24
    • 2019-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-10
    相关资源
    最近更新 更多