经历过一段时间的c++学习,已经掌握了一定的基础,但是,对于多态与虚函数还是有无法理解的地方,对于迭代器的灵活使用还是没有比较熟练的掌握。我认为,写代码最重要的是思路,有了思路,一切都是畅通无阻的,编程语法只是一个微不足道的问题。
下面分享一道基础练习题。
“姓名”和“性别”是教师、学生共有的属性,“职称”和“工资”是教师特有的属性, “班级”和“成绩”是学生特有的。 请用类模拟。
#include <iostream>
#include <string.h>
using namespace std;
class NameSex
{
public:
string Name, Sex;
NameSex(string N, string S);
};
NameSex::NameSex(string N, string S)
{
Name = N;
Sex = S;
}
class Teacher : public NameSex
{
private:
string Position;
int Salary = 0;
public:
Teacher(string N, string S, string P, int Sal);
void Show()
{
cout << "教师姓名:" << Name << " 性别:" << Sex << " 职称" << Position << " 工资:" << Salary << endl;
}
};
Teacher::Teacher(string N, string S, string P, int Sal) : NameSex(N, S)
{
Position = P;
Salary = Sal;
}
class Student : public NameSex
{
private:
string sClass;
int Score = 0;
public:
Student(string N, string S, string sC, int Sco);
void Show()
{
cout << "学生姓名:" << Name << " 性别:" << Sex << " 班级" << sClass << " 成绩:" << Score << endl;
}
};
Student::Student(string N, string S, string sC, int Sco) : NameSex(N, S)
{
sClass = sC;
Score = Sco;
}
int main()
{
Teacher T("张", "男", "讲师", 2000);
Student S("朱", "男", "1班", 99);
T.Show();
S.Show();
return 0;
}
现在的代码在可能在许多方面上还存在着不足,以后会慢慢来改。