zoukankan      html  css  js  c++  java
  • 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;

    }

  • 相关阅读:
    使用序列化实现对象的拷贝
    SQL连接查询深度探险
    关于ArrayList和Vector区别
    list_arrayList三种遍历性能比较
    Java过滤器与SpringMVC拦截器之间的关系与区别
    遍历map 哪种方式更加高效。
    Http请求中Content-Type讲解以及在Spring MVC中的应用
    sql语句练习50题
    在js中初始化select数据
    java浮点数剖析
  • 原文地址:https://www.cnblogs.com/hnrainll/p/2050206.html
Copyright © 2011-2022 走看看