OOP in C Language


// cool.h 头文件,定义父类和子类。
typedef struct {
char* name;
int age;
} Person;
void setName(Person* person, char* name);
char* getName(Person* person);
void setAge(Person* person, int age);
int getAge(Person* person);

typedef struct {
Person person;
char** listOfCourses;
int numOfCourses;
} Student;
void setListOfCourses(Student* student, char* listOfCourses[], int numOfCourses);
void printListOfCourses(Student* student);

// person.c 源文件,父类行为原型的实现。
#include <stdlib.h>
#include <string.h>
#include "cool.h"

void setName(Person* person, char* name) {
person->name = malloc(sizeof(strlen(name) + 1));
strcpy(person->name, name);
}

char* getName(Person* person) {
return person->name;
}

void setAge(Person* person, int age) {
person->age = age;
}

int getAge(Person* person) {
return person->age;
}
// student.c源文件,子类行为原型的实现。
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "cool.h"

void setListOfCourses(Student* student, char* listOfCourses[], int numOfCourses) {
int i;
char** temp;
student->numOfCourses = numOfCourses;
temp = malloc(numOfCourses * sizeof(char*));
student->listOfCourses = temp;

for (i = 0; i < numOfCourses; i++) {
*temp = malloc(sizeof(strlen(*listOfCourses) + 1));
strcpy(*temp, *listOfCourses);
temp++;
listOfCourses++;
}
}

void printListOfCourses(Student* student) {
int i;
char** temp;

temp = student->listOfCourses;
printf("%s' major is ", ((Person*)student)->name);
for (i = 0; i < student->numOfCourses-1; i++) {
printf("%s, ", *temp++);
}
printf("and %s.\n", *temp);
}

// main.c 主源文件,观察多态现象。
#include <string.h>
#include <stdio.h>
#include "cool.h"

int main() {
Person* lily;
lily = malloc(sizeof(Person));
setName(lily, "Lily");
setAge(lily, 19);
printf("%s is %d years old.\n", getName(lily), getAge(lily));

Student* peter;
peter = malloc(sizeof(Student));
setName((Person*) peter, "Peter");
setAge((Person*) peter, 20);
printf("%s is %d years old.\n", getName((Person*) peter), getAge((Person*) peter));


char* listOfCourses[] = { "poem", "music", "movie" };
int numOfCourses = sizeof(listOfCourses) / sizeof(listOfCourses[0]);
setListOfCourses(peter, listOfCourses, numOfCourses);
printListOfCourses(peter);

return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值