C++之 多继承

在学校里有老师和学生,他们都是人,我么应该创建一个名为 Person 的基类和两个名为 Teacher 和Student 的子类,后两者是从前者继承来的

有一部分学生还教课挣钱(助教),也就是同时存在着两个"是一个"关系,我们需要写一个 TeschingStudent 类让它同时继承 Teacher 类和 Student 类,换句话说,就是需要使用多继承。

cpp 复制代码
// 基本语法:
class TeachingStudent : public Student, public Teacher
{ ... }
cpp 复制代码
#include<iostream>
#include<string>
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,I`m"<<name<<"。\n\n"; 
}


Teacher::Teacher(std::string theName,std::string theClass):Person(theName)
{
	classes=theClass;
}
void Teacher::teach()
{
	std::cout<<name<<"教"<<classes<<"。\n\n"; 	
}
void Teacher::introduce()
{
	std::cout<<"大家好,我是"<<name<<",我教"<<classes<<"。\n\n"; 
}


Student::Student(std::string theName,std::string theClass):Person(theName)
{
	classes=theClass;
}
void Student::attendClass()
{
	std::cout<<name<<"加入"<<classes<<"学习。\n\n";
}
void Student::introduce()
{
	std::cout<<"大家好,我是"<<name<<",我在"<<classes<<"学习\n\n"; 
}


TeachingStudent::TeachingStudent(std::string theName,std::string classTeaching,std::string classAttending): Teacher(theName,classTeaching),Student(theName,classAttending)
{
	
}
void TeachingStudent::introduce()
{
		std::cout<<"大家好,我是"<<Student::name<<",我教"<<Teacher::classes<<",";
		std::cout<<"同时我在"<<Student::classes<<"学习。\n\n";
}


int main()
{
	Teacher  teacher("小红","入门班");
	Student student("兰兰","C++入门班");
	TeachingStudent teachingStudent("茗茗","C++入门班级","C++进阶班");
	
	teacher.introduce();
	teacher.teach();
	
	student.introduce();
	student.attendClass();
	
	teachingStudent.introduce();
	teachingStudent.teach();
	teachingStudent.attendClass();
	
	return 0;
}

注意:

  • 在使用多继承的时候,一定要特别注意继承了基类的多少个副本。
  • 在使用多继承的时候,最安全最简明的做法是从没有任何属性且只有抽象方法的类开始继承。
  • 按照上边这么做可以让你远离后代子类可能拥有好几个基类属性的问题。
  • 这样的类又叫做接口( interface )。

未完待续。。。

相关推荐
博客18001 天前
酷宝的使用方法,超好用的免费界面库,C++、MFC可用
c++·mfc·界面库·库来帮·酷宝
郝学胜_神的一滴1 天前
CMake 026:属性体系精讲、四大作用域全解 & 实战代码落地
c++·cmake
众少成多积小致巨2 天前
JNI (Java Native Interface) 技术手册中文参考指南
android·java·c++
clint4566 天前
C++进阶(1)——前景提要
c++
夜悊6 天前
C++代码示例:进制数简单生成工具
c++
郝学胜_神的一滴6 天前
CMake 021: IF 条件判据详诠
c++·cmake
_wyt0017 天前
洛谷 B3930 [GESP202312 五级] 烹饪问题 题解
c++·gesp
玖玥拾7 天前
C/C++ 数据结构(七)栈、容器适配器
c语言·数据结构·c++··容器适配器
один but you7 天前
constexpr函数
c++
凡人叶枫7 天前
Effective C++ 条款41:了解隐式接口和编译期多态
java·开发语言·c++·effective c++