1. 引言
C语言作为一门历史悠久的编程语言,一直以来以其简洁、高效的特点受到广泛欢迎。然而,C语言并非面向对象编程(OOP)的传统语言。杜茂康所著的《C语言面向对象程序设计》一书,为读者提供了一种在C语言中实现面向对象编程的方法。本书习题丰富,有助于读者巩固知识,提升编程能力。本文将对书中的一些课后习题进行解析,帮助读者解锁难题。
2. 习题解析
2.1 习题一:定义一个简单的类
题目描述:定义一个名为Student的类,包含学号、姓名和成绩三个属性。
解析:
#include <stdio.h>
typedef struct {
int id;
char name[50];
float score;
} Student;
int main() {
Student stu1;
stu1.id = 1;
strcpy(stu1.name, "张三");
stu1.score = 90.5;
printf("学号:%d\n", stu1.id);
printf("姓名:%s\n", stu1.name);
printf("成绩:%f\n", stu1.score);
return 0;
}
2.2 习题二:继承与多态
题目描述:定义一个基类Person,包含姓名和年龄属性;定义一个派生类Student,继承自Person类,并添加成绩属性。在main函数中创建一个Student对象,并打印其信息。
解析:
#include <stdio.h>
#include <string.h>
typedef struct {
char name[50];
int age;
} Person;
typedef struct {
Person p;
float score;
} Student;
void printInfo(Person *person) {
printf("姓名:%s\n", person->name);
printf("年龄:%d\n", person->age);
}
int main() {
Student stu;
stu.p.name[0] = '\0';
stu.p.age = 20;
strcpy(stu.p.name, "李四");
stu.score = 95.0;
printInfo(&stu.p);
printf("成绩:%f\n", stu.score);
return 0;
}
2.3 习题三:虚函数与纯虚函数
题目描述:定义一个基类Shape,包含一个纯虚函数draw;定义一个派生类Circle和Rectangle,分别重写draw函数。
解析:
#include <stdio.h>
typedef struct {
float area;
} Shape;
typedef struct {
Shape base;
float radius;
} Circle;
typedef struct {
Shape base;
float width, height;
} Rectangle;
void draw(Shape *shape) {
if (shape->area > 0) {
printf("绘制图形\n");
}
}
int main() {
Circle c;
c.base.area = 3.14 * 1 * 1;
c.radius = 1;
draw(&c.base);
Rectangle r;
r.base.area = r.width * r.height;
r.width = 2;
r.height = 4;
draw(&r.base);
return 0;
}
3. 总结
本文对《C语言面向对象程序设计》一书中的一些课后习题进行了详细解析。通过这些解析,读者可以更好地理解C语言面向对象编程的概念和方法。在实际编程过程中,还需不断练习,加深对面向对象编程的理解。
