c++之多繼承

什麼時候要用到多繼承  ?

當遇到的問題無法只用" 是一個 " 關係來描述的時候 , 就用多繼承 ;

例如 : 老師與學生 就繼承自person類 ,但助教既是學生 ,也是老師 ;所以使用多繼承 ;

基本語法 : 

class TeachStduent : public Student ,public Teacher {...};


#include <string>
#include <iostream>

class Person{
public :
Person(std::string theName);
void introduce();
protected:
std::string name;
};


class Teacher :public Person{
public :
Teacher(std::string theName,std::string theClass);


void teach();
void introduce();
protected:
std::string classes;
};
class Student :public Person{
public :
Student(std::string theName,std::string theClass);


void attendClass();
void introduce();


protected:
std::string classes;
};


class TeachingStudent : public Student ,public Teacher {
public :
TeachingStudent(std::string theName , std::string classTeaching , std::string classAttending);


void introduce();
};
Person::Person(std::string theName){
name = theName;
}
void Person::introduce(){
std::cout <<"hello everyone ,i am "<<name<<"\n";
}


Teacher ::Teacher(std::string theName,std::string theClass):Person(theName){
classes = theClass;
}


void Teacher::teach(){
std::cout <<name <<"teach "<<classes<<"\n\n";
}
void Teacher::introduce(){
std::cout <<"hello everyONe,im "<< name<<", i Teach "<<classes<<"\n";
}
Student::Student(std::string theName,std::string theClasses):Person(theName){
classes = theClasses;
}
void Student::introduce(){
std::cout <<"hello all,i am "<<name <<" , i study with "<<classes <<"\n\n";
}
void Student::attendClass(){
std::cout <<name <<"jump "<<classes <<"\n\n";
}
TeachingStudent::TeachingStudent(std::string theName,std::string classTeach,std::string classAttend):Teacher(theName,classTeach),Student(theName,classAttend){
}


void TeachingStudent::introduce(){
std::cout << "hello all , i am "<<Student::name <<",, i teach "<<Teacher::classes<<",,";
std::cout <<" same time i study at "<< Student::classes << "\n\n";
}

int _tmain(int argc, _TCHAR* argv[])
{
Teacher teacher("小甲魚","C++入門班");
Student stu("nightWish","c++基礎班");
TeachingStudent teachStu("丁丁","c++入門踏板","c++進階班");

teacher.introduce();
teacher.teach();

stu.introduce();
stu.attendClass();

teachStu.introduce();
teachStu.attendClass();
teachStu.teach();

system("pause");  }


虛繼承 : virtual inheritance ;

語法 :

class Teacher : virtual Public Person {....} 


修改後的TeachStudent應該 ;

class Teacher(std::string theName,std::string classes):virtual public Person{...}

class TeachStudent (std::string theName,std::string teachClasses,std::string attendClass):Teacher(theName,teachClasses),Student(theName,attendClass),Person(theName){.....};

 

虛繼承的類不能拷貝父類的屬性 , 子類如果要使用該屬性必須繼承該類,而不是它的子類中獲取;
















發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章