繁体   English   中英

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

[英]Objects in C - Structs Syntax Related

我最近在阅读有关创建类似于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”一词),考虑到一开始就没有typedef 我认为它与初始化有关(我不知道像构造函数一样),但这是我第一次在定义中看到struct = {...,...,...}。 我已经看到,当您初始化以下示例中的结构时:

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

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

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

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

3)这是一个小疑问,这意味着,我对前两个更感兴趣。 无论如何,它就开始了……在第一个代码的开头,它说了类似“ //将您放置在private之后的内容:这里”。 这是为什么? 如何将它们设为私有?


仅此而已,我将不胜感激,这让我想了好几个小时! 在此先感谢您,祝您度过愉快的一天!

1)不用担心成员是函数,仅此而已:

点(。)在结构初始化程序中是什么意思?

2)在

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

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

真的等同于

double d = 1;

在其中,将double替换为struct S {int i;},将s替换为d,并将1初始化为结构体{0}的初始化程序。 现在,将其与点语法结合起来。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM