类继承

#include <iostream>

#include <iomanip>

using namespace std;

class Shape {

private:

double x, y;

public:

Shape(double x = 0, double y = 0) : x(x), y(y) {}

};

class Rectangle : public Shape {

private:

double length, width;

public:

Rectangle(double x, double y, double length, double width) : Shape(x, y), length(length), width(width) {}

double GetArea() { return length * width; }

};

class Circle : public Shape {

private:

double radius;

public:

Circle(double x, double y, double radius) : Shape(x, y), radius(radius) {}

double GetArea() { return 3.14 * radius * radius; }

};

class Square : public Rectangle {

public:

Square(double x, double y, double side) : Rectangle(x, y, side, side) {}

};

int main() {

double length, width, radius, side;

cin >> length >> width;

cin >> radius;

cin >> side;

Rectangle rectangle(0, 0, length, width);

Circle circle(0, 0, radius);

Square square(0, 0, side);

cout << rectangle.GetArea() << endl;

cout << circle.GetArea() << endl;

cout << square.GetArea() << endl;

return 0;

}

  • Rectangle类公有继承自Shape类。它有两个私有成员变量lengthwidth,分别表示矩形的长和宽。
  • 构造函数接受四个参数,前两个参数用于初始化基类Shape的坐标点,后两个参数用于初始化矩形的长和宽。
  • GetArea函数用于计算矩形的面积,通过返回length乘以width的值来实现。
  • Circle类也公有继承自Shape类。它有一个私有成员变量radius,表示圆的半径。
  • 构造函数接受三个参数,前两个参数用于初始化基类Shape的坐标点,第三个参数用于初始化圆的半径。
  • GetArea函数用于计算圆的面积,根据圆的面积公式π * r * r(这里π取 3.14)计算并返回结果。
全部评论

相关推荐

xdm怎么说&nbsp;要被拷打了&nbsp;担心是KPI
丹田:面就完了,就当日薪四位数的大佬免费给给你面试。
点赞 评论 收藏
分享
湫湫湫不会java:1.在校经历全删了2.。这些荣誉其实也没啥用只能说,要的是好的开发者不是好好学生3.项目五六点就行了,一个亮点一俩行,xxx技术解决,xxx问题带来xxx提升。第一页学历不行,然后啥有价值的信息也没有,到第二页看到项目了,第一个项目九点,第二个项目像凑数的俩点。总体给人又臭又长,一起加油吧兄弟
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务