一、多继承的概念
多继承即一个子类可以有多个父类,它继承了多个父类的特性。 C++ 类可以从多个类继承成员,语法如下:
class <派生类名> : <继承方式1><基类名1>,<继承方式2><基类名2>,…
{
<派生类类体>
};
举例
#include <iostream>
using namespace std;
// 基类 Shape
class Shape
{
public: //派生类可以访问
void setWidth(int w)
{
width = w;
}
void setHeight(int h)
{
height = h;
}
protected: //**派生类可以访问**
int width;
int height;
};
// 基类 PaintCost
class PaintCost
{
public:
int getCost(int area)
{
return area * 70;
}
};
// 派生类
class Rectangle: public Shape, public PaintCost
{
public:
int getArea()
{
return (width * height);
}
};
int main(void)
{
Rectangle Rect;
int area;
Rect.setWidth(5);
Rect.setHeight(7);
area = Rect.getArea();
// 输出对象的面积
cout << "Total area: " << Rect.getArea() << endl;
// 输出总花费
cout << "Total paint cost: $" << Rect.getCost(area) << endl;
return 0;
}
结果:
PS C:\Users\newuser\Desktop\C++\第五天C++> g++ .\D多 继承.cpp
PS C:\Users\newuser\Desktop\C++\第五天C++> ./a
Total area: 35
Total paint cost: $2450
二、多继承举例
1.C++ 继承:
1.当创建一个类时,您不需要重新编写新的数据成员和成员函数,
只需指定新建的类继承了一个已有的类的成员即可。
这个已有的类称为基类(父类),新建的类称为派生类(子类)。
2.访问控制和继承:
派生类可以访问基类中所有的非私有成员(public protected)。 因此基类成员如果不想被派生类的成员函数访问,
则应在基类中声明为 private。
3.访问接收 public protected private
同一个类 yes yes yes
派生类 yes yes no
外部的类 yes no no
4.一个派生类继承了所有的基类方法,但下列情况除外:
基类的
构造函数、析构函数和拷贝构造函数
。
基类的重载运算符
。
基类的友元函数
。
5.1
公有继承(public)
:当一个类派生自公有基类时,基类的公有成员也是派生类的公有成员,基类的保护成员也是派生类的保护成员,基类的私有成员不能直接被派生类访问,但是可以通过调用基类的公有和保护成员来访问。
5.2
保护继承(protected)
: 当一个类派生自保护基类时,基类的公有和保护成员将成为派生类的保护成员。
5.3
私有继承(private)
:当一个类派生自私有基类时,基类的公有和保护成员将成为派生类的私有成员。
三、代码示例
#include <iostream>
using namespace std;
//基类 (一个大的应用)
class Animal
{
public:
void sleep_1(int sleep)
{
this->sleep = sleep;
}
void eat_2(int eat)
{
this->eat = eat;
}
static string name; //静态变量在数据段,需要类外初始化
void shared()
{
cout<<"name = "<<this->name<<endl;
cout<<"sleep="<<this->sleep<<endl;
cout<<"eat ="<<this->eat<<endl;
}
private:
int sleep;
int eat;
};
string Animal::name = "123";
//派生类(可以使用大的应用,并修改和添加。。。)
class Dog :public Animal //公有方式继承
{
public:
void get_sleep()
{
cout<<"子类程序="<<Animal::name<<endl;
}
};
class FF //其他类,只可以访问公有
{
public:
//和基类没有任何交集,但可以访问基类公有
string Name = Animal::name; //调用静态变量的方式
void show()
{
cout<<"其他类打印基类值"<<Name<<endl;
}
};
int main(int argc, char const *argv[])
{
Dog st1;
st1.eat_2(110); //子类赋值父类
st1.sleep_1(112); //子类赋值父类
st1.get_sleep(); //子类打印
st1.shared(); //打印父类内容
FF ff;
ff.show(); //其他类访问基类
return 0;
}
结果
PS C:\Users\newuser\Desktop\C++\第五天C++> ./a
子类程序=123
name = 123
sleep=112
eat =110
其他类打印基类值123