class derived-class: access-specifier base-class
#include
using namespace std;
// 基类
class Shape
{
public:
void setWidth(int w)
{
width = w;
}
void setHeight(int h)
{
height = h;
}
protected:
int width;
int height;
};
// 派生类
class Rectangle: public Shape
{
public:
int getArea()
{
return (width * height);
}
};
int main(void)
{
Rectangle Rect; // 定义一个派生类Rectangle 的对象Rect
Rect.setWidth(5); //为对象Rect赋初值
Rect.setHeight(7);
cout << "Total area: " << Rect.getArea() << endl;// 输出对象的面积
return 0;
}

| public | protected | private | |
|---|---|---|---|
| 同一个类 / 友元类 | √ | √ | √ |
| 派生类 | √ | √ | × |
| 外部的类 | √ | × | × |
| 基类 成员的访问属性 | 派生 成员的访问属性 |
|---|---|
| public继承 | public → public private → private protected → protected |
| private 继承 | public → private private → private protected → private |
| protected 继承 | public → protected private → private protected → protected |
class <派生类名>:<继承方式1><基类名1>,<继承方式2><基类名2>,…
{
<派生类类体>
};
#include
using namespace std;
// 第1个基类 Shape
class Shape
{
public:
void setWidth(int w)
{
width = w;
}
void setHeight(int h)
{
height = h;
}
protected:
int width;
int height;
};
// 第2个基类 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;
}
