glg*_*lgl 64
不,因为功能不是数据.但是您可以在结构中定义函数指针.
struct foo {
int a;
void (*workwithit)(struct foo *);
}
Run Code Online (Sandbox Code Playgroud)
tch*_*hap 22
你无法真正在C语言中的结构中声明内容.这不是C++或任何其他OO语言,其中一个对象封装了某种范围.
C结构是非常简单的对象,它只是管理一块内存的语法糖.当你创建新的struct"instance"时struct A a;,编译器只是根据它的大小保留堆栈空间,当你这样做时a.member,编译器知道该成员的偏移量,所以它跳转到&a该成员的+ offset.这些偏移通常不仅仅是前面成员大小的总和,因为编译器通常会在结构中添加一些填充位以使其更好地与内存对齐.
希望它有所帮助.你显然对C结构有点太多了:-)
drc*_*uck 11
我写这篇文章是因为我正在寻找一种方法来教授一些面向对象“风格”的 C 编程,以完成一门非常简单的数据结构课程。我不想教 C++,因为我不想继续解释它更高级的功能。
但我想探索如何在低级语言/运行时中实现Python 中使用的 OO 模式。通过解释 C 中发生的事情,学生可能会更好地理解 Python OO 运行时模式。因此,我超出了上面的第一个答案,并改编了/sf/answers/885000371/中的一些模式,但以某种方式稍微阐明了 OO 运行时模式。
首先,我在point.c中使用“构造函数”创建了“类” :
#include <stdio.h>
#include <stdlib.h>
struct point
{
int x;
int y;
void (*print)(const struct point*);
void (*del)(const struct point*);
};
void point_print(const struct point* self)
{
printf("x=%d\n", self->x);
printf("y=%d\n", self->y);
}
void point_del(const struct point* self) {
free((void *)self);
}
struct point * point_new(int x, int y) {
struct point *p = malloc(sizeof(*p));
p->x = x;
p->y = y;
p->print = point_print;
p->del = point_del;
return p;
}
Run Code Online (Sandbox Code Playgroud)
然后我导入该类,从该类构造一个对象,使用该对象,然后在main.c中销毁该对象
#include "point.c"
int main(void)
{
struct point * p3 = point_new(4,5);
p3->print(p3);
p3->del(p3);
}
Run Code Online (Sandbox Code Playgroud)
感觉很“Pythonic in C”。
不,您不能在 C 程序中的 struct 内部使用函数。我写了一个代码并将其保存为 .c 和 .cpp。.cpp 文件符合预期并按预期工作,但 .c 文件甚至无法编译。
这是代码供您参考。将其保存为 .cpp 一次,然后运行它。然后保存与 .c 相同的代码并编译它。你会得到一个编译错误。
#include <stdio.h>
struct C {
void Test(int value) {
static int var = 0;
if (var == value)
printf("var == value\n");
else
printf("var != value\n");
var = value;
}
};
int main() {
C c1;
C c2;
c1.Test(100);
c2.Test(100);
int ii;
scanf("%d",&ii);
}
Run Code Online (Sandbox Code Playgroud)