【发布时间】: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页面。它通过示例解释了所有内容。
-
因为这样的问题可以通过阅读文档轻松回答。这对社区没有多大好处,而且之前已经回答过了。似乎您在问题上投入了更多精力,而不是对其进行研究。不过我没有投反对票。