C语言面向对象编程:面向对象设计与实现问答
问:面向对象编程的核心概念是什么?
答:
问:如何创建一个类和对象?
立即学习“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!\n"); } };
实战案例:学生信息管理系统
// 学生类 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 < list->numStudents; i++) { printf("Name: %s, Age: %d, GPA: %.2f\n", list->students[i].name, list->students[i].age, list->students[i].gpa); } }
以上就是C语言面向对象编程:面向对象设计与实现问答的详细内容,更多请关注php中文网其它相关文章!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号