前言
大半夜的又整了个活!
算是写的第二个C++代码,反正不是码农,随便写着玩玩,但无论怎样,用户体验第一,安全性第一!
好像不能兼得哦。反正安全性我也不太会,那就安全性第二吧。用户体验第一!
功能介绍
这个工程包括四个类,分别是人员类、学生类、教师类和学生教师混合类。
学生类和教师类虚继承人员类,混合类多继承学生类和教师类。
每个类包含各自的toString
函数,拥有较完善的键入界面。
结果展示
使用界面
创建人员对象
创建混合对象并打印
好了,懒得展示了,直接嫖吧
代码区
人员类
#include<iostream>
#include<sstream>
using namespace std;
//人员类
class Person {
public:
Person(string name, int age) :m_name(name), m_age(age) { }
string toString() {
string str = m_name + "'s age is ";
str += std::to_string(m_age);
str += ".\n";
return str;
}
private:
int m_age;
string m_name;
};
两个虚继承
//学生类
class Student : virtual public Person {
public:
Student(int score, string name, int age) : m_score(score), Person(name, age) { }
string toString(int key) {
string str = "And his score is ";
str += std::to_string(m_score);
str += ".\n";
return str;
}
string toString() {
return Person::toString() + toString(1);
}
private:
int m_score;
};
//教师类
class Teacher : virtual public Person {
public:
Teacher(int salary, string name, int age) : m_salary(salary), Person(name, age) { }
string toString(int key) {
string str = "And his salary is ";
str += std::to_string(m_salary);
str += ".\n";
return str;
}
string toString() {
return Person::toString() + toString(1);
}
private:
int m_salary;
};
一个多继承
//教师学生混合人员
class StuStaff : public Student, public Teacher {
public:
StuStaff(int score, int salary, string name, int age)
: Student(score, name, age), Teacher(salary, name, age), Person(name, age) { }
string toString() {
return Person::toString() + Student::toString(1) + Teacher::toString(1);
}
};
交互菜单
//交互菜单
void makeMenu() {
cout << "+----菱形继承模拟系统----+" << endl;
cout << "| 0.退出系统 |" << endl;
cout << "| 1.创建人员对象并打印 |" << endl;
cout << "| 2.创建学生对象并打印 |" << endl;
cout << "| 3.创建教师对象并打印 |" << endl;
cout << "| 4.创建混合对象并打印 |" << endl;
cout << "+------------------------+" << endl;
cout << "请选择操作:";
}
按键交互
//按键交互
void keyDown() {
int key;
cin >> key;
switch (key) {
case(0):
cout << "退出成功" << endl;
exit(0);
break;
case(1): {
cout << "请输入姓名和年龄:";
string name;
int age;
cin >> name >> age;
Person person(name, age);
cout << person.toString();
break;
}
case(2): {
cout << "请输入姓名,年龄和分数:";
string name;
int age, score;
cin >> name >> age >> score;
Student student(score, name, age);
cout << student.toString();
break;
}
case(3): {
cout << "请输入姓名,年龄和工资:";
string name;
int age, salary;
cin >> name >> age >> salary;
Teacher teacher(salary, name, age);
cout << teacher.toString();
break;
}
case(4): {
cout << "请输入姓名,年龄,分数和工资:";
string name;
int age, score, salary;
cin >> name >> age >> score >> salary;
StuStaff stu(score, salary, name, age);
cout << stu.toString();
break;
}
default:
break;
}
}
主函数
int main() {
while (1) {
makeMenu();
keyDown();
system("pause");
system("cls");
}
return 0;
}
整活结束!