文章目录
实现了学生类,派生了小学生类,实现如下:
头文件
源文件(截取构造函数部分)
Student.hpp
#pragma once
#include <string>
class Student
{
private:
std::string name;
int stu_no;
public:
Student(const std::string& _name = "none", int _stu_no = 0);
void SetName(std::string _name);
void SetStuNo(float _stu_no);
std::string GetName();
float GetStuNo();
void Print_Student_info();
};
class Primary_Student : public Student
{
private:
float language;
float math;
public:
Primary_Student(float _la = 0.0,float _ma = 0.0,const std::string& _name = "none",int _stu_no = 0);
Primary_Student(float _la,float _ma,const Student& stu);
float average();
};
Student.cpp
#include "Student.h"
#include <iostream>
using namespace std;
//基类构造函数
Student::Student(const string& _name, int _stu_no) :name(_name), stu_no(_stu_no) {}
//派生类构造函数
Primary_Student::Primary_Student(
float _la,float _ma,
const std::string& _name,int _stu_no
) : Student(_name, _stu_no)
{
language = _la;
math = _ma;
}
//派生类构造函数
Primary_Student::Primary_Student(
float _la,float _ma,const Student& stu
) :Student(stu), language(_la), math(_ma){}
void Student::SetName(std::string _name) {
this->name = _name;
}
void Student::SetStuNo(float _stu_no) {
this->stu_no = _stu_no;
}
string Student::GetName() {
return name;
}
float Student::GetStuNo() {
return stu_no;
}
void Student::Print_Student_info() {
cout << "Name=" << name << " stu_no=" << stu_no << endl;
}
float Primary_Student::average() {
float _average = (language + math) * 0.50;
return _average;
}
main.cpp
#include "Student.h"
#include <iostream>
using namespace std;
int main(int argc, char* argv[]) {
Student stu1("鲁班", 001);
Student stu2;
stu2.SetName("狄仁杰");
stu2.SetStuNo(002);
cout << "Name=" << stu1.GetName() << " stu_no=" << stu1.GetStuNo() << endl;
cout << "Name=" << stu2.GetName() << " stu_no=" << stu2.GetStuNo() << endl;
stu2.Print_Student_info();
Primary_Student pri_stu1(88.0, 85.1, "蔡文姬", 3);
Primary_Student pri_stu2(88.0, 85.1, "亚索", 4);
Primary_Student pri_stu3(88.0, 85.1, stu2);
cout << pri_stu1.GetName() << "\t average = " << pri_stu1.average() << endl;
cout << pri_stu2.GetName() << "\t average = " << pri_stu2.average() << endl;
cout << pri_stu3.GetName() << "\t average = " << pri_stu3.average() << endl;
pri_stu1.Print_Student_info();
pri_stu2.Print_Student_info();
pri_stu3.Print_Student_info();
}
截图演示: