C++面向对象编程:Person类和Student类的示例详解
C++面向对象编程:Person类和Student类的示例详解
本文将通过一个简单的代码示例,帮助你理解C++面向对象编程中的类、继承、构造函数以及公私有成员等概念。
代码示例cpp#include #include
using namespace std;
// 定义Person类class Person {private: string ID; // 身份证号 string name; // 姓名 string sex; // 性别 string birthday; // 出生年月日
public: // 构造函数,用于初始化私有成员 Person(string id, string n, string s, string b) : ID(id), name(n), sex(s), birthday(b) {}
// 公有成员函数,用于获取私有成员的值 string getID() { return ID; }
string getName() { return name; }
string getSex() { return sex; }
string getBirthday() { return birthday; }};
// 定义Student类,继承自Person类class Student : public Person {private: string className; // 班级 float score; // 专业成绩
public: // 构造函数,需要显式调用父类构造函数,并初始化新增私有成员 Student(string id, string n, string s, string b, string c, float sc) : Person(id, n, s, b), className(c), score(sc) {}
// 公有成员函数,用于获取新增私有成员的值 string getClass() { return className; }
float getScore() { return score; }};
int main() { // 创建Student类的实例 Student *stu = new Student('1234567890', 'John Doe', 'Male', '2003-10-01', '电科班', 95.5);
// 输出各个私有成员的值 cout << 'ID: ' << stu->getID() << endl; cout << 'Name: ' << stu->getName() << endl; cout << 'Sex: ' << stu->getSex() << endl; cout << 'Birthday: ' << stu->getBirthday() << endl; cout << 'Class: ' << stu->getClass() << endl; cout << 'Score: ' << stu->getScore() << endl;
delete stu;
return 0;}
代码解析
-
Person类: * 包含身份证号、姓名、性别、出生年月日等私有成员变量。 * 定义了构造函数用于初始化这些成员变量。 * 提供了公有的成员函数用于获取这些成员变量的值。
-
Student类: * 继承自Person类,拥有Person类的所有成员变量和成员函数。 * 新增了班级和专业成绩两个私有成员变量。 * 定义了自己的构造函数,并调用父类的构造函数初始化继承的成员变量。 * 提供了公有的成员函数用于获取新增成员变量的值。
-
main函数: * 创建了一个Student类的实例,并传入相关信息。 * 调用Student类的成员函数获取各个成员变量的值并输出。
总结
这段代码演示了如何使用C++定义类、实现继承关系、使用构造函数初始化成员变量以及定义公私有成员等面向对象编程的基本概念。通过学习这段代码,你将对C++面向对象编程有更深入的理解。
原文地址: https://www.cveoy.top/t/topic/14F 著作权归作者所有。请勿转载和采集!