一个派生类可以继承多个基类
以下代码演示派生类zzj继承两个基类people、student
#include <iostream>
using namespace std;
class people
{
private:
int m_age;
public:
people(int age);
void print();
~people();
};
people::people(int age)
{
cout << "people 构造" << endl;
m_age = age;
}
void people::print()
{
cout << "年龄:" << m_age << endl;
}
people::~people()
{
cout << "people 析构" << endl;
}
class student
{
private:
int m_score;
public:
student(int score);
void print();
~student();
};
student::student(int score)
{
cout << "student 构造" << endl;
m_score = score;
}
void student::print()
{
cout << "分数:" << m_score << endl;
}
student::~student()
{
cout << "student 析构" << endl;
}
class zzj : public people, public student
{
private:
string m_name;
public:
zzj(int age, int score, string name);
void print();
~zzj();
};
zzj::zzj(int age, int score, string name) : people(age), student(score)
{
cout << "zzj 构造" << endl;
m_name = name;
}
void zzj::print()
{
people::print();
student::print();
cout << "姓名:" << m_name << endl;
};
zzj::~zzj()
{
cout << "zzj 析构" << endl;
}
int main()
{
zzj z(19, 98, "ZZJ");
z.print();
return 0;
}
需要注意75、76行在调用两个基类print函数时出现了两个基类成员函数重名
需要加上类名和域解析符::来区分
运行结果如下: