编写一个C++课设作业,要求能够实现一定的功能,有一定的目的与意义,稍长,包括继承与派生、多态性与虚函数。
时间: 2023-09-30 18:10:36 浏览: 40
以下是一个简单的C++课设作业示例,它实现了一个图形计算器:
1. 基类:Shape
* 成员函数:getArea(获取面积)、getPerimeter(获取周长)、printInfo(输出基本信息)
2. 派生类:Rectangle
* 成员变量:length、width
* 成员函数:getArea(获取面积)、getPerimeter(获取周长)、printInfo(输出基本信息)
3. 派生类:Circle
* 成员变量:radius
* 成员函数:getArea(获取面积)、getPerimeter(获取周长)、printInfo(输出基本信息)
其中,Shape类是所有图形的基类,Rectangle和Circle类分别继承自Shape类,并且重载了基类的虚函数getArea、getPerimeter和printInfo。
代码示例:
```c++
#include <iostream>
using namespace std;
class Shape {
public:
virtual double getArea() {
return 0;
}
virtual double getPerimeter() {
return 0;
}
virtual void printInfo() {
cout << "This is a shape." << endl;
}
};
class Rectangle : public Shape {
public:
double length;
double width;
Rectangle(double l, double w) {
length = l;
width = w;
}
double getArea() {
return length * width;
}
double getPerimeter() {
return 2 * (length + width);
}
void printInfo() {
cout << "This is a rectangle." << endl;
cout << "Length: " << length << endl;
cout << "Width: " << width << endl;
cout << "Area: " << getArea() << endl;
cout << "Perimeter: " << getPerimeter() << endl;
}
};
class Circle : public Shape {
public:
double radius;
Circle(double r) {
radius = r;
}
double getArea() {
return 3.14 * radius * radius;
}
double getPerimeter() {
return 2 * 3.14 * radius;
}
void printInfo() {
cout << "This is a circle." << endl;
cout << "Radius: " << radius << endl;
cout << "Area: " << getArea() << endl;
cout << "Perimeter: " << getPerimeter() << endl;
}
};
int main() {
Shape* shape1 = new Rectangle(5, 10);
Shape* shape2 = new Circle(5);
shape1->printInfo();
shape2->printInfo();
delete shape1;
delete shape2;
return 0;
}
```
在上述示例中,我们定义了一个Shape类作为基类,并定义了getArea、getPerimeter和printInfo等虚函数。Rectangle和Circle类分别继承自Shape类,并重载了基类的虚函数以实现自己的功能。在main函数中,我们分别实例化了一个Rectangle对象和一个Circle对象,并通过基类指针来调用各自的方法。这个示例展示了多态性和虚函数的作用,使得我们可以通过基类指针来调用派生类的方法。