C语言面向对象编程:面向对象设计与实现问答
问:面向对象编程的核心概念是什么?
答:
- 封装:将数据和方法绑定在一起,隐藏实现细节。
- 继承:派生类继承基类的方法和属性。
- 多态:对象可以根据其类型执行不同的方法。
问:如何创建一个类和对象?
答:
// 声明一个类
struct Person {
char* name;
int age;
};
// 创建一个对象
struct Person john = {"John", 30};
问:如何使用继承?
答:
// Base class (基类)
struct Shape {
double area;
};
// Derived class (派生类)
struct Circle : public Shape {
double radius;
};
问:如何实现多态?
答:
// 基类
struct Animal {
virtual void makeSound() = 0; // 纯虚函数
};
// 派生类
struct Dog : public Animal {
void makeSound() {
printf("Woof!
");
}
};
实战案例:学生信息管理系统
// 学生类
struct Student {
char* name;
int age;
float gpa;
};
// 学生列表类
struct StudentList {
struct Student* students;
int numStudents;
};
// 创建学生列表
struct StudentList* createStudentList() {
struct StudentList* list = malloc(sizeof(struct StudentList));
list->students = NULL;
list->numStudents = 0;
return list;
}
// 向列表中添加学生
void addStudent(struct StudentList* list, struct Student* student) {
list->students = realloc(list->students, (list->numStudents + 1) * sizeof(struct Student));
list->students[list->numStudents++] = *student;
}
// 打印列表中的学生信息
void printStudentList(struct StudentList* list) {
for (int i = 0; i numStudents; i++) {
printf("Name: %s, Age: %d, GPA: %.2f
",
list->students[i].name, list->students[i].age, list->students[i].gpa);
}
}
以上就是C语言面向对象编程:面向对象设计与实现问答的详细内容,更多请关注知识资源分享宝库其它相关文章!
版权声明
本站内容来源于互联网搬运,
仅限用于小范围内传播学习,请在下载后24小时内删除,
如果有侵权内容、不妥之处,请第一时间联系我们删除。敬请谅解!
E-mail:dpw1001@163.com
发表评论