类的继承与派生

#include<iostream>
#include<string>
using namespace std;

class School
{
protected:
int Number;
string Name; //c++中碰到字符数组就用string类型来定义
public:
School(int num, string name) {Number=num; Name=name; } // 基类的构造函数
};

class Student:public School // 定义继承基类的派生类也很重要
{
private:
int Class_Num;
int Total;
public:
    //使用初始化列表的方法初始化自身,和传参给基类

Student(int x,int y, int a, string b):School(a,b) {Class_Num = x; Total = y;}
void Display(){
cout << "编号," << "姓名," << "班级," << "总成绩" << endl;
cout << Number << "," << Name << "," << Class_Num  << "," << Total << endl;
}
};

void main()
{
Student B(4,678,2020150601,"zhangxiaomeng"); // 注意传参的顺序
B.Display(); // 调用函数必须有小括号()
}
// 函数没有返回值就用void,函数结束没有分号;

 

posted on 2022-10-26 20:22  进取  阅读(11)  评论(0编辑  收藏  举报