C++的继承是一种面向对象编程的概念,允许一个类(称为子类或派生类)继承另一个类(称为父类或基类)的属性和方法。这意味着子类可以重用父类的代码,并且可以扩展或修改它。
下面是一个简单的C++继承实例:
```cpp
#include <iostream>
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() {
Rectangle rect;
rect.setWidth(5);
rect.setHeight(7);
// 计算矩形的面积
cout << "Total area: " << rect.getArea() << endl;
return 0;
}
在这个例子中,`Rectangle`类继承了`Shape`类的属性和方法,包括`setWidth()`和`setHeight()`。然后,`Rectangle`类添加了自己的方法`getArea()`来计算矩形的面积。