给我生成几道关于c++面向对象设计的实验题及相关答案
时间: 2023-06-04 10:08:31 浏览: 105
我可以为您生成一些关于C++面向对象设计的实验题及相关答案,请参考以下内容:
1. 实验题目:设计一个图形类,包括圆形和矩形两种形状,能够计算图形的面积和周长。写一个程序测试该类的功能。
解答:可以定义一个Shape类作为基类,包含计算面积和周长的虚函数,Circle和Rectangle类继承自Shape类,实现各自的计算方法和其他属性。示例代码如下:
```
#include <iostream>
#include <cmath>
using namespace std;
const double PI = 3.14159265358979323846;
class Shape {
public:
virtual double area() const = 0;
virtual double perimeter() const = 0;
};
class Circle : public Shape {
private:
double radius;
public:
Circle(double r) : radius(r) {}
double area() const {
return PI * radius * radius;
}
double perimeter() const {
return 2 * PI * radius;
}
};
class Rectangle : public Shape {
private:
double width;
double height;
public:
Rectangle(double w, double h) : width(w), height(h) {}
double area() const {
return width * height;
}
double perimeter() const {
return 2 * (width + height);
}
};
int main() {
Shape *p1 = new Circle(5);
Shape *p2 = new Rectangle(4, 3);
cout << "圆的面积和周长:" << p1->area() << "," << p1->perimeter() << endl;
cout << "矩形的面积和周长:" << p2->area() << "," << p2->perimeter() << endl;
delete p1;
delete p2;
return 0;
}
```
2. 实验题目:设计一个日期类,能够记录年、月、日,能够格式化输出为“年-月-日”的形式,能够判断两个日期之间的间隔天数。写一个程序测试该类的功能。
解答:可以定义一个Date类,包含年、月、日三个成员变量和输出、计算间隔天数的方法。输出方法可以使用cout流+控制符实现格式化输出,计算间隔天数的方法需要利用闰年、平年的特点进行计算。示例代码如下:
```
#include <iostream>
using namespace std;
class Date {
private:
int year;
int month;
int day;
public:
Date(int y, int m, int d) : year(y), month(m), day(d) {}
friend ostream &operator<<(ostream &os, const Date &dt) {
os << dt.year << "-" << dt.month << "-" << dt.day;
return os;
}
int interval(const Date &other) const {
int days = 0;
static int monthDays[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int year1 = this->year, month1 = this->month, day1 = this->day;
int year2 = other.year, month2 = other.month, day2 = other.day;
// 计算两个日期之间的天数
while (year1 < year2 || month1 < month2 || day1 < day2) {
if (year1 == year2 && month1 == month2) {
days += day2 - day1;
break;
}
if (day1 == monthDays[month1 - 1]) {
if (month1 == 2 && year1 % 4 == 0 && year1 % 100 != 0 || year1 % 400 == 0) {
days += 29 - day1;
} else {
days += monthDays[month1 - 1] - day1;
}
day1 = 1;
month1++;
}
if (month1 > 12) {
year1++;
month1 = 1;
}
days++;
day1++;
}
return days;
}
};
int main() {
Date d1(2020, 10, 1);
Date d2(2021, 1, 1);
cout << "日期1:" << d1 << endl;
cout << "日期2:" << d2 << endl;
cout << "两个日期之间的间隔天数:" << d1.interval(d2) << endl;
return 0;
}
```
希望这些实验题与答案对您有所帮助。如有任何疑问,欢迎随时与我交流。
阅读全文