【问题标题】:Objects in C - Structs Syntax RelatedC 中的对象 - 结构语法相关
【发布时间】:2017-01-22 22:31:24
【问题描述】:

我最近在阅读有关创建类似于 c++ 对象的方法的文章,但在 C 中,我遇到了一些非常好的示例。然而,有一段代码让我思考了好几个小时,因为这是我第一次看到这种语法,而且我在 Google 上没有找到类似的东西......


块本身就是这个:

struct stack {
     struct stack_type * my_type;
     // Put the stuff that you put after private: here
};
struct stack_type {
     void (* construct)(struct stack * this); // This takes uninitialized memory
     struct stack * (* operator_new)(); // This allocates a new struct, passes it to construct, and then returns it
     void (*push)(struct stack * this, thing * t); // Pushing t onto this stack
     thing * (*pop)(struct stack * this); // Pops the top thing off the stack and returns it
     int this_is_here_as_an_example_only;
}Stack = {
    .construct = stack_construct,
    .operator_new = stack_operator_new,
    .push = stack_push,
    .pop = stack_pop
};

假设所有设置为指针的函数都定义在其他地方,我的疑问如下:

1) 为什么点 ( '.' ) 是什么意思,或者在初始化函数指针时它的目的是什么? (例如:.construct = stack_construct

2) 为什么结构体定义末尾的'Stack'后面有等号,为什么还有'以外的东西; ' (在这种情况下是 'Stack' ),考虑到开头没有 typedef 的事实? 我认为它与初始化有关(就像构造函数,我不知道),但这是我第一次在定义中看到 struct = {...,...,...} 。我已经看到,当您像以下示例一样初始化结构时:

typedef struct s{
int a;
char b;
}struc;

void main(){
    struc my_struct={12,'z'};
}

但这不在结构的主要声明中,而且 {} 中仍然没有 '=' em>,与第一个示例不同,它显示类似...

struc my_struct={ a = 12,
                  b = 'z'};

3) 这是一个小疑问,意思是,我对前两个更感兴趣。不管怎样,就这样吧…… 在第一个代码的开头,它说类似'// 把你放在私有后面的东西:这里'。这是为什么?这将如何使它们私有化?


就是这样,我将不胜感激,这让我思考了好几个小时!提前致谢,祝您有美好的一天!

【问题讨论】:

  • 彻底阅读this页面。它通过示例解释了所有内容。
  • 因为这样的问题可以通过阅读文档轻松回答。这对社区没有多大好处,而且之前已经回答过了。似乎您在问题上投入了更多精力,而不是对其进行研究。不过我没有投反对票。

标签: c oop struct syntax


【解决方案1】:

1) 不要担心成员是函数,只是这样:

What does dot (.) mean in a struct initializer?

2) 在

struct S {int i;}
s = {0};

第一行命名了一个可用于声明和初始化变量的类型。

它真的相当于

double d = 1;

您将 double 替换为 struct S {int i;},将 s 替换为 d,并将 1 替换为结构的初始值设定项 {0}。现在将它与点语法结合起来。

它只是也定义了 struct S 的副作用。

更新: 关于 3),我不认为私有它们指的是访问控制的实现,而是指在 C++ 中,您通常会在类的私有部分列出数据成员,所以我将其理解为在类型标识元素之后添加数据成员的说明。

【讨论】:

    猜你喜欢
    • 2021-06-12
    • 1970-01-01
    • 2016-03-19
    • 1970-01-01
    • 2015-07-28
    • 2018-06-19
    • 2018-09-14
    • 2017-10-25
    相关资源
    最近更新 更多