c - C 中的对象 - 结构体语法相关

标签 c oop struct syntax

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

<小时/>

block 本身就是这个:

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) 这是一个小疑问,这意味着我对前两个更感兴趣。不管怎样,就这样吧…… 在第一个代码的开头,它写着“//将您在 private: 之后放置的内容放在此处”。这是为什么?这将如何使它们成为私有(private)的?

<小时/>

仅此而已,我会很感激任何事情,这让我思考了几个小时!预先感谢,祝您有美好的一天!

最佳答案

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}。现在将其与点语法结合起来。

它只是具有定义结构 S 的副作用。

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

关于c - C 中的对象 - 结构体语法相关,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41796867/

相关文章:

c - 在 C 中转置锯齿状数组?

java - 使用 Java 继承

c - 获取输入并将其分配给指针数组中的结构,指向每个结构。

c - 从结构中释放分配的内存

c - 如何为未知大小的结构动态分配内存?

c - socket(PF_INET, SOCK_RAW, AF_INET) 使用 IGMP?

c - 如何计算一个文本字符串中有多少个不同的字母?

c - 解释具有未命名结构的 union 的理论[已关闭]

typescript - 有什么理由在 TypeScript 中使用静态/私有(private)静态方法吗?

java - 潜在无用的对象