随笔 - 21  文章 - 0  评论 - 0  阅读 - 2461

类的继承与派生

#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   进取  阅读(15)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示