栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++(十二)类的继承(简单继承)

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++(十二)类的继承(简单继承)

文章目录

Student.hppStudent.cppmain.cpp
实现了学生类,派生了小学生类,实现如下:

头文件

源文件(截取构造函数部分)

Student.hpp
#pragma once
#include 

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

截图演示:

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/714478.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号