多重继承

  F10和F11组合查看函数调用流程,F10顺序执行,F11跟进去函数
# include <iostream>
# include <string.h>
using namespace std;
class Teacher//声明teacher类
{
public:
	Teacher(string nam,int a,string t)//构造函数
	{
		name=nam;
		age=a;
		title=t;
	}
void display()
{
	cout<<"name: "<<name<<endl;
    cout<<"age: "<<age<<endl;
	cout<<"title: "<<title<<endl;
}
protected:
	string name;
	int age;
	string title;
};
//2.
class Student//定义student类
{
public:
	Student( string nam,char s,float sco)//构造函数
	{
	//strcpy(name1,nam);
	name1=nam;
	sex=s;
	score=sco;
	}
	void display1()
	{
	cout<<"name: "<<Student::name1<<endl;
	cout<<"sex: "<<sex<<endl;
	cout<<"score: "<<score<<endl;
	}
protected:
	string name1;
	char sex;
	float score;
};
//3.
class Graduate:public Teacher,public Student//声明多重继承的派生类graduate
{
public:
	Graduate(string nam,int a,char s,string t,float sco,float w):Teacher(nam,a,t),Student(nam,s,sco),wage(w){}
	void show()
	{
		cout<<"name: "<<name<<endl;
		cout<<"age: "<<age<<endl;
		cout<<"sex: "<<sex<<endl;
		cout<<"score: "<<score<<endl;
		cout<<"title: "<<title<<endl;
		cout<<"wages: "<<wage<<endl;
	}
private:
	float wage;
};

int main()//main函数进行调试
{
Graduate grad1("wang_li",24,'f',"assistant",89.5,1200);
grad1.show();
return 0;
}


运行结果:

说说:我把它:strcpy(name1,nam)改成name1=nam;


用name和name1是为了是编译通过而采用的并不高明的方法,没有实用意义,因为绝大多数的基类已经编写好的已经存在的用户可以利用他而无法修改它,解决方法,在show函数中引用数据成员时指明其作用域,

cout << "name:" << Student::name << endl;


代码:

#include<iostream>
#include<string>
using namespace std;
class Teacher
{
public:
	Teacher(string nam, int a, string t)
	{
		name = nam;
		age = a;
		title = t;
	}
	void display()
	{
		cout << "name:" << name << endl;
		cout << "age:" << age << endl;
		cout << "title:" << title << endl;
	}
protected:
	string name;
	int age;
	string title;
};
class Student
{
public:
	Student(string nam, char s, float sco)
	{
		name = nam;
		sex = s;
		score = sco;
	}
	void display1()
	{
		cout << "name:" << Student::name << endl;
		cout << "sex:" << sex << endl;
		cout << "score:" << score << endl;
	}
protected:
	string name;
	char sex;
	float score;
};

class Graduate :public Teacher, public Student
{
public:
	Graduate(string nam, int a, char s, string t, float sco, float w) :Teacher(nam, a, t), Student(nam, s,sco), wage(w){}
	void show()
	{
		cout << "name:" << Teacher::name << endl;
		cout << "age" << age << endl;
		cout << "sex:" << sex << endl;
		cout << "score:" << score << endl;
		cout << "title:" << title << endl;
		cout << "wage:" << wage << endl;
	}
private:
	float wage;
};
int main()
{
	Graduate grad1("wang_li", 24, 'f', "assistant", 89.5, 1200);
	grad1.show();
	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值