面向对象-继承与派生程序练习
时间: 2024-06-13 21:06:42 浏览: 8
当我们使用面向对象编程时,继承和派生是非常重要的概念。继承是指一个类可以从另一个类中继承属性和方法,而派生则是指从一个已有的类中创建一个新的类。下面是一个简单的C++继承和派生的示例程序:
```
#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;
}
```
在这个程序中,我们定义了一个基类Shape,它有两个属性width和height,以及两个方法setWidth和setHeight。然后我们定义了一个派生类Rectangle,它继承了Shape类,并添加了一个新的方法getArea,用于计算矩形的面积。在主函数中,我们创建了一个Rectangle对象Rect,并设置它的宽度和高度,然后输出它的面积。
这只是一个简单的示例程序,你可以根据自己的需要进行修改和扩展。如果你想深入了解C++的继承和派生,可以参考C++的相关教程和书籍。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)