• C++继承应用例程


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

    class NameString{//声明类namestring
    private:
    char *str;
    public:
    //声明构造函数,不能有返回类型
    NameString(char *s="...")
    {
    str
    = new char[strlen(s)+1];
    strcpy(str,s);
    // cout<<"构造 NameString OK!"<<endl;
    }
    //声明成员函数
    void print()
    {
    cout
    <<str;//打印私有成员
    }
    //析构函数,不能有返回类型和形参
    ~NameString()
    {
    // cout<<"析构 NameString OK!"<<endl;
    delete str;
    }
    };

    class Student{ //声明类
    protected:
    int StudentNO;
    NameString Name;
    //类类型的成员变量
    int Scores;
    static int total_Scores;//静态成员变量
    static int total_Num;
    public:
    //以列表形式初始化
    Student(int a,char *b,int c):StudentNO(a),Name(b),Scores(c)
    {
    total_Scores
    += c;
    total_Num
    ++;
    // cout<<"构造 Student OK!"<<endl;
    }

    void print()
    {
    cout
    <<StudentNO<<'\t';
    Name.print();
    //这是一个类类型的成员变量,本类不能直接访问string类的成员
    cout<<'\t'<<Scores<<endl;
    }

    void average()
    {
    cout
    <<"Average:"<<total_Scores/total_Num<<endl;
    }

    static void total_disp()//静态成员函数
    {
    cout
    <<"Total_Scores:"<<total_Scores<<endl;
    cout
    <<"Total_Num:"<<total_Num<<endl;
    }

    };

    class Graduate:public Student{
    private:
    char *teacher;
    public:
    Graduate(
    int a,char *b,int c,char *s):Student(a,b,c)
    {
    teacher
    = new char[strlen(s)+1];
    strcpy(teacher,s);
    }
    ~Graduate()
    {
    delete teacher;
    }

    void print()
    {
    cout
    <<StudentNO<<'\t';
    Name.print();
    //这是一个类类型的成员变量,本类不能直接访问string类的成员
    cout<<'\t'<<Scores;
    cout
    <<'\t'<<teacher<<endl;
    }
    };
    //定义静态成员变量,并进行初始化
    int Student::total_Scores = 0;
    int Student::total_Num = 0;

    int main()
    {
    Graduate st1(
    1,"wen",94,"chin");
    Graduate st2(
    2,"hao",100,"chin");
    Graduate st3(
    3,"lin",100,"chin");
    #if 0
    Student st1(
    1,"wen",94,"chin");
    Student st2(
    2,"hao",100,"chin");
    Student st3(
    3,"lin",100,"chin");
    #endif
    cout
    <<"学号"<<'\t'<<"姓名"<<'\t'<<"成绩"<<'\t'<<"导师"<<endl;
    st1.print();
    st2.print();
    st3.print();

    Student::total_disp();

    st1.average();

    return 0;

    }

  • 相关阅读:
    .NET简谈互操作(七:数据封送之介绍)
    C# utf8编码时转换成shiftjis时出现乱码问题的处理
    .NET简谈特性(代码属性)
    著名Channel 9 主持人Robert Green 采访微软一站式示例代码库录像
    SharePoint 2007运行 Edit In DataSheet 时在IE 6下页面卡死的分析和处理方法
    截图工具
    Resharper上手指南
    .NET简谈互操作(三:基础知识之DllImport特性)
    .NET简谈互操作(五:基础知识之提升平台调用性能)
    深度训练(DotNet专场)
  • 原文地址:https://www.cnblogs.com/hnrainll/p/2050206.html
Copyright © 2020-2023  润新知