mindfocus 发表于 2013-2-1 13:56:08

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);setListOfCourses(peter, listOfCourses, numOfCourses);printListOfCourses(peter);return 0;}
页: [1]
查看完整版本: OOP in C Language