Virtual Functions

内容:


说明:

纯虚函数以及静态变量的使用

示例代码:

// Virtual_Functions.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <string>
#include <vector>
#include <iostream>
using namespace std;

class Person
{
public:
    virtual void getdata() = 0;
    virtual void putdata() = 0;
protected:
    string name;
    int age;

};

class Professor : public Person
{
public:
    Professor()
    {
        cur_id = ++id;
    }
    void getdata()
    {
        cin >> name >> age >> publications;
    }
    void putdata()
    {
        cout << name << " " << age << " " << publications << " " << cur_id << endl;
    }
private:
    static int id;
    int publications;
    int cur_id;
};
int Professor::id = 0;

class Student : public Person
{
public:
    Student()
    {
        cur_id = ++id;
    }
    void getdata()
    {
        cin >> name >> age;
        cin.ignore();

        for( int i = 0; i < 6; i++ )
        {
            int data;
            cin >> data;
            score.push_back( data );
        }
    }
    void putdata()
    {
        int sum = 0;
        cout << name << " " << age << " ";

        for( int i = 0; i < 6; i++ )
        {
            sum += score[i];
        }

        cout << sum << " " << cur_id << endl;
    }
protected:
    static int id;
    vector<int> score;
    int cur_id;
};
int Student::id = 0;

//by zhaocl
int main()
{
    int n;
    cin >> n;

    while( n-- )
    {
        int type;
        cin >> type;

        if( type == 1 )
        {
            Professor pf;
            pf.getdata();
            pf.putdata();
        }
        else if( type == 2 )
        {
            Student st;
            st.getdata();
            st.putdata();
        }
    }

    system( "pause" );
    return 0;
}


知识点:

1、纯虚函数的使用

2、静态变量的使用

猜你喜欢

转载自blog.csdn.net/zhao3132453/article/details/80053188