C++ string 类和继承:Person 类和 Student 类示例

本示例展示了 C++ 中如何使用 string 类来存储字符串,并使用继承来创建 Person 类和 Student 类,演示了类成员变量、构造函数、继承和成员函数的使用。

字符串类 string 的基本用法

#include <iostream>
#include <string>

using namespace std;

int main() {
    string str = "Thank you";
    str += " very much!";
    cout << str << endl;
    str = "Love C++!";
    cout << str << endl;
    return 0;
}

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 类

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;
    }
};

main 函数

int main() {
    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;
}

说明

  • 该示例展示了如何使用 string 类来存储字符串,并使用继承来创建 Person 类和 Student 类。
  • Person 类包含个人信息,Student 类继承自 Person 类,并添加了班级和成绩信息。
  • 每个类都定义了构造函数和成员函数,用来访问和修改私有成员变量。
  • main 函数中创建了一个 Student 对象,并调用了成员函数来输出所有成员变量的值。

请注意,这是一个基于您的设定的伪代码示例,可能需要根据实际情况进行调整。

C++ string 类和继承:Person 类和 Student 类示例

原文地址: https://www.cveoy.top/t/topic/13C 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录