case5:繼承和派生的作用舉例_1.0版本(不使用繼承)
阿新 • • 發佈:2018-11-02
在面向物件物件程式設計C++的書中有這樣一個案例:
(1)我們通過Student類和Teacher類,不使用繼承來實現上面的功能:
(1) main.cpp
/************************************************************************ * Object-Oriented Programming C++ * @title School 1.0 * @author Haoaowei *Email:
[email protected] * ************************************************************************/ #include "teacher.h" #include "student.h" int main() { Teacher ta("TA"); //呼叫Teacher類 Teacher tb("TB"); Student s1("S1",2005); //初始化類Student Student s2("S2",2006); ta.teach("C++"); //類Teacher中的成員函式 tb.teach("英語"); s1.learn("C++"); //學生學習 s2.learn("英語"); tb.talk(ta,"請你吃飯去啊"); //老師類之間的通訊 ta.talk(tb,"好啊"); s2.talk(s1,"我想去"); //學生類之間的通訊 s1.talk(s2,"我也想去"); ta.talk(s1,"一起去吧"); //通過函式的過載實現 tb.talk(s2,"你先回家做作業"); ta.eat("包子"); //類Teacher中的成員函式 tb.eat("餃子"); s1.eat("豆漿");//類Student中的成員函式 s2.doHomework("英語"); //類Student的函式 return 0; }
(2) student.h
#ifndef STUDENT_H_INCLUDED #define STUDENT_H_INCLUDED #include "string" using std::string; class Student { public: Student( string name="hao",int grade=2011); //建構函式 ~Student(){};//解構函式 //成員函式 string getName() const {return name;} //類外獲取私有成員 void learn(string course); void talk(Student S,string stm); void eat(string food); void doHomework(string course); private: string name; int grade; }; #endif
(3) student.cpp
#include "student.h"
#include "iostream"
using namespace std;
Student::Student( string name,int grade):name(name),grade(grade) {}//建構函式
void Student::learn(string course) //成員函式,老師教
{
cout<<grade<<"級學生"<<name <<"學習"<<course <<endl;
}
void Student::talk(Student S,string stm) //學生類之間的通訊
{
cout<<"學生"<<name<<"對 學生" << S.name << "說: "<< stm <<endl;
}
void Student::eat(string food)
{
cout <<"學生"<<name<<"吃"<<food <<endl;
}
void Student::doHomework(string course)
{
cout <<"學生"<<name<<"做"<<course <<endl;
}
(4) teacher.h
#ifndef TEACHER_H_INCLUDED
#define TEACHER_H_INCLUDED
#include "student.h"
#include "string"
using std::string;
class Teacher
{
public:
Teacher( string name = "hao"); //建構函式
~Teacher(){};//解構函式
//成員函式
void teach(string stm);
void talk(Teacher T,string stm);
void talk(Student S,string stm); //通過函式的過載
void eat(string food);
private:
string name;
};
#endif
(5) teacher.cpp
#include "teacher.h"
#include "iostream"
using namespace std;
Teacher::Teacher( string name):name(name) {} //建構函式
void Teacher::teach(string stm) //成員函式,老師教
{
cout<<"教師"<<name <<"教"<<stm <<endl;
}
void Teacher::talk(Teacher T,string stm)
{
cout <<"老師"<<name <<"對 老師"<<T.name <<"說: "<<stm<<endl;
}
void Teacher::talk(Student S,string stm) //通過函式的過載
{
cout <<"老師"<< name <<"對 學生"<<S.getName()<<"說: "<<stm<<endl; //S.name 無法直接訪問到
}
void Teacher::eat(string food)
{
cout <<"老師"<<name<<"吃"<<food <<endl;
}
執行結果:
不通過繼承和派生可以實現上面的功能,但是存在的問題: