c++学习第二天:继承
1、概念
1、概念
派生类继承自基类,派生类不需要重写成员变量和函数,继承基类的成员变量和函数。
2、特点
- 一个类可以派生自多个类,即一个子类有多个父类
- 不同访问修饰符继承
公有继承
public | protect | private | |
---|---|---|---|
基类 | √ | √ | √ |
派生类类 | public | protected | private |
其它类 | public | × | × |
保护有继承
public | protect | private | |
---|---|---|---|
基类 | √ | √ | √ |
派生类类 | protected | protected | × |
其它类 | × | × | × |
私有继承
public | protect | private | |
---|---|---|---|
基类 | √ | √ | √ |
派生类类 | private | private | × |
其它类 | × | × | × |
#include <iostream>
using namespace std;
class shape
{
public:
void set(double l, double w)
{
length = l;
width = w;
}
protected:
double length;
double width;
} ;
class paintCost
{
public:
double cost(double area)
{
return area * 3;
}
};
class rectangle : public shape, public paintCost
{
public:
double getArea()
{
return width *length;
}
};
int main(void)
{
rectangle r;
double area;
r.set(3, 4);
area = r.getArea();
cout << "面积为" << area << endl;
cout << "面积的3倍为" << r.cost(area) << endl;
}