出一个c++包含(继承与派生、结构体、数组
时间: 2023-08-08 19:07:15 浏览: 58
以下是一个包含继承与派生、结构体、数组的C++代码示例:
```c++
#include <iostream>
using namespace std;
// 定义一个基类Shape
class Shape {
public:
void setWidth(int w) {
width = w;
}
void setHeight(int h) {
height = h;
}
protected:
int width;
int height;
};
// 定义一个派生类Rectangle
class Rectangle: public Shape {
public:
int getArea() {
return (width * height);
}
};
// 定义一个结构体Student
struct Student {
string name;
int age;
float score;
};
int main() {
// 声明一个Rectangle对象r
Rectangle r;
// 设置r的宽和高
r.setWidth(5);
r.setHeight(10);
// 输出r的面积
cout << "Rectangle area is: " << r.getArea() << endl;
// 声明一个结构体数组s,存储三个学生信息
Student s[3];
s[0].name = "Tom";
s[0].age = 18;
s[0].score = 90.5;
s[1].name = "Jerry";
s[1].age = 19;
s[1].score = 88.0;
s[2].name = "Alice";
s[2].age = 20;
s[2].score = 95.0;
// 循环输出数组s中的学生信息
for(int i = 0; i < 3; i++) {
cout << "Student " << i+1 << ": " << endl;
cout << " Name: " << s[i].name << endl;
cout << " Age: " << s[i].age << endl;
cout << " Score: " << s[i].score << endl;
}
return 0;
}
```
在上面的代码中,我们定义了一个基类Shape,它有两个成员变量width和height。我们又定义了一个派生类Rectangle,继承自Shape,并且新增了一个成员函数getArea(),用于计算矩形的面积。我们还定义了一个结构体Student,它有三个成员变量name、age和score。最后,我们在main函数中创建了一个Rectangle对象r,并且设置了其宽和高,然后输出了其面积。接着,我们定义了一个结构体数组s,存储了三个学生的信息,然后循环输出了学生的信息。