实训C++语言设计——Student学生类设计、继承、重写

来源:互联网 发布:网络协查函怎么开 编辑:程序博客网 时间:2024/04/30 13:01

平台:VC++ 2005 测试通过!
.vcproj
这是使用应用程序向导生成的 VC++ 项目的主项目文件。
它包含生成该文件的 Visual C++ 的版本信息,以及有关使用应用程序向导选择的平台、配置和项目功能的信息。
StdAfx.h, StdAfx.cpp
这些文件用于生成名为 twod.pch 的预编译头 (PCH) 文件和名为 StdAfx.obj 的预编译类型文件。
这些都是使用应用程序向导生成的 VC++ 文件故不列出
我只列出程序主要部分!

/*
   本例展示了两个抽象数据类型CStudent、CGradstu的简单
   继承关系, 作为子类的CGradstu继承了父类的属性和方法,
   体现数据和代码的重用.此外,子类根据自己的需要
   "重写(overwrite)"了父类的同名方法.
*/
#include <iostream>
#include <string>
#include <list>
using namespace std;

class CStudent {
public:
   CStudent(long stuid, string nm, string year, string dept);
   virtual void  print() const;
protected:
/*If it is protected , its name can be used only
   1. by member functions and friends of the class in which
       it is declared
   2. and by member functions and friends of classes derived
   from this class*/
   long     _stuid;
   string  _year; string  _name; string  _dept;
};

class CGradstu : public CStudent {
/*puclic inheritance means that the protected and public
    members of CStudent are to be inherited as protected
 and public member of CGradstu*/
public:
   CGradstu( long stuid, string nm, string year,
                   string dept, string sp, string th);
   virtual void  print() const;
protected:
   string  _support;  
   string  _thesis;
};

CStudent::CStudent(long stuid, string nm, string year, string dept)
   :_name(nm), _stuid(stuid), _year(year), _dept(dept){}

CGradstu::CGradstu (long stuid, string nm, string year,
                                     string dept, string sp, string th):
CStudent(stuid, nm, year, dept), _support(sp), _thesis(th){}

void CStudent::print() const {
   cout << _stuid << " , " << _name
            << " , " << _year << " , " << _dept << endl;       
}
/*子类根据自己的需要overwrite从父类继承来的方法*/
void CGradstu::print() const {
   CStudent::print(); //base class info is printed
   cout << _support << " , " << _thesis  << endl;
}
 

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

#include "stdafx.h"
#include "CStudent.h"

/*用户的global function*/
void output(list<CStudent> stulist){
     list<CStudent>::iterator iter = stulist.begin();
        list<CStudent>::iterator end = stulist.end();
  while( iter != end )
             (*iter++).print();  
}

int _tmain(int argc, _TCHAR* argv[])
{
 CStudent stu1(2004112001, "张三", "三年级", "软件工程");
 CStudent stu2(2004112002, "李四", "三年级", "网络工程");
 CGradstu grad1(10112001, "王五" , "研究生", "计算数学",
         "TA", "求解博弈nash均衡");
 list<CStudent> StuList;
    StuList.push_back(stu1);
 StuList.push_back(stu2);
 StuList.push_back(grad1);
 output(StuList);
 
    //grad1.print();
 

 return 0;
}