【发布时间】:2021-05-20 13:43:10
【问题描述】:
我正在学习 C 语言,最近学习了如何使用 C 编写 OOP。除了用于创建新类的结构类型的名称外,大部分内容对我来说并不难理解。
我的教科书使用struct dummy_t 进行前向声明,使用typedef struct {...} dummy_t 进行定义。在我的理解中,这是两种不同的类型,因为前者是struct dummy 类型,而后者是struct 类型,没有名称标签,但教科书中的示例代码运行良好。
所以我特意修改了示例代码,使结构名称的区别更加清晰。以下是我尝试过的代码行。
//class.h
struct test_a;
struct test_a * test_init(void);
void test_print(struct test_a*);
//class.c
#include <stdio.h>
#include <stdlib.h>
typedef struct dummy{
int x;
int y;
} test_b;
test_b * test_init(void){
test_b * temp = (test_b *) malloc(sizeof(test_b));
temp->x = 10;
temp->y = 11;
return temp;
}
void test_print(test_b* obj){
printf("x: %d, y: %d\n", obj->x, obj->y);
}
//main.c
#include "class.h"
int main(void){
struct test_a * obj;
obj = test_init();
test_print(obj);
return 0;
}
// It printed "x: 10, y: 10"
如您所见,我使用struct test_a 进行前向声明,使用typedef struct dummy {...} test_b 进行定义。
我想知道为什么我没有收到编译错误并且它起作用了。
【问题讨论】:
-
如果您在 class.c 中
#include<class.h>,您将得到所需的编译器错误,因为编译器可以比较函数签名并告诉您它们冲突。 -
您拥有的代码应该会生成一个编译器警告,指出您将错误的类型传递给
test_print,因此您可能需要打开编译器诊断。 -
这被称为未定义的行为......其中包括“似乎可以工作”的情况。
-
@0___________ 这是在 C 中实现私有封装的一种众所周知的方式。私有封装如何不是 OOP? OO 是一种设计程序的方式,而不是一种编写程序的方式......
-
@0___________ 我不相信模拟程序设计是可能的。无论语言如何,您要么有程序设计,要么没有。
标签: c oop struct compilation