實驗題目:第11章習題9程序驗證
一暇仲、實驗目的
- 上機驗證《C++程序設計(第3版)》第11章習題9。
- 復習C++繼承與派生相關知識疚漆。
二酣胀、實驗內容
詳見一刁赦、實驗目的
。
三闻镶、設計和編碼
1. 本實驗用到的理論知識
C++繼承與派生
2. 編碼
程序清單如下
// ex3.cpp
// Encoding: UTF-8
/*
* 3.分別聲明Teacher(教師)類和Cadre(干部)類甚脉,
* 采用多重繼承方式由這兩個類派生出新類Teacher_Cadre(教師兼干部)類。要求:
* (1) 在兩個基類中都包含姓名铆农、年齡牺氨、性別、地址墩剖、電話等數據成員波闹。
* (2) 在Teacher類中還包含數據成員title(職稱),在Cadre類中還包含數據成員post(職務)涛碑。
* 在Teacher_Cadre類中還包含數據成員wages(工資)精堕。
* (3) 對兩個基類中的姓名、年齡蒲障、性別歹篓、地址、電話等數據成員用相同的名字揉阎,
* 在引用這些數據成員時庄撮,指定作用域。
* (4) 在類體中聲明成員函數毙籽,在類外定義成員函數洞斯。
* (5) 在派生類Teacher_Cadre的成員函數show中調用Teacher類中的display函數,
* 輸出姓名坑赡、年齡烙如、性別、職稱毅否、地址亚铁、電話,然后再用cout語句輸出職務與工資螟加。
*/
#include <string>
#include<stdio.h>
#include <iostream>
using namespace std;
class Teacher
{
public:
Teacher(string nam, int a, char s, string tit, string ad, string t);
void display();
protected:
string name;
int age;
char sex;
string title;
string addr;
string tel;
};
Teacher::Teacher(string nam, int a, char s, string tit, string ad, string t) : name(nam), age(a), sex(s), title(tit), addr(ad), tel(t) {}
void Teacher::display()
{
cout << "name:" << name << endl;
cout << "age" << age << endl;
cout << "sex:" << sex << endl;
cout << "title:" << title << endl;
cout << "address:" << addr << endl;
cout << "tel:" << tel << endl;
}
class Cadre
{
public:
Cadre(string nam, int a, char s, string p, string ad, string t);
void display();
protected:
string name;
int age;
char sex;
string post;
string addr;
string tel;
};
Cadre::Cadre(string nam, int a, char s, string p, string ad, string t) : name(nam), age(a), sex(s), post(p), addr(ad), tel(t) {}
void Cadre::display()
{
cout << "name:" << name << endl;
cout << "age:" << age << endl;
cout << "sex:" << sex << endl;
cout << "post:" << post << endl;
cout << "address:" << addr << endl;
cout << "tel:" << tel << endl;
}
class Teacher_Cadre : public Teacher, public Cadre
{
public:
Teacher_Cadre(string nam, int a, char s, string tit, string p, string ad, string t, float w);
void show();
private:
float wage;
};
Teacher_Cadre::Teacher_Cadre(string nam, int a, char s, string t, string p, string ad, string tel, float w) : Teacher(nam, a, s, t, ad, tel), Cadre(nam, a, s, p, ad, tel), wage(w) {}
void Teacher_Cadre::show()
{
Teacher::display();
cout << "post:" << Cadre::post << endl;
cout << "wages:" << wage << endl;
}
int main()
{
Teacher_Cadre te_ca("Wang-li", 50, 'f', "prof.", "president", "135 Beijing Road,Shanghai", "(021)61234567", 1534.5);
te_ca.show();
return 0;
}
四徘溢、運行與測試
1. 測試環(huán)境
運行環(huán)境:Windows 20H2, i7-9750H @ 2.60GHz, 16GB RAM
編譯器:gcc version 8.1.0 (x86_64-posix-seh-rev0, Built by MinGW-W64 project)
編譯命令:-g
運行終端:cmd
2. 在調試程序的過程中遇到的問題與解決方案
暫未發(fā)現異常。
3. 程序的運行結果
運行結果(符合預期)
D:\OneDrive - mail2.sysu.edu.cn\MyDocuments\code\DSA\week03>ex3
name:Wang-li
age50
sex:f
title:prof.
address:135 Beijing Road,Shanghai
tel:(021)61234567
post:president
wages:1534.5
六捆探、總結與心得
繼承與派生是C++面向對象程序設計中重要知識然爆,不容小覷。
七黍图、參考資料
- 譚浩強. C++程序設計[M]. 3 版. 清華大學出版社, 2015.