PTA 使用类计算矩形的面积 (10 分)

定义并实现一个矩形类,有长和宽两个属性,由成员函数计算矩形的面积。

矩形类Rectang接口定义如下:

class Rectangle {
public:
    void setLength(int l);//设置矩形的长度
    void setWidth(int w); //设置矩形的宽度
    int getArea();    //计算并返回矩形的面积
private:
    int length, width;  //矩形的长度和宽度	
};

请实现Rectangle类的成员函数。

裁判测试程序样例:

#include <iostream>
using namespace std;

class Rectangle {
public:
    void setLength(int l);//设置矩形的长度
    void setWidth(int w); //设置矩形的宽度
    int getArea();        //计算并返回矩形的面积
private:
    int length, width;    //矩形的长度和宽度	
};

int main()
{
    Rectangle r;
    int len, w;
    cin >> len >> w;
    r.setLength(len);
    r.setWidth(w);
    cout << r.getArea() << "\n";

    return 0;
}

/* 你的代码将嵌在这里 */

输入样例:

10 20

输出样例:

200
   void Rectangle::setLength(int l)//设置矩形的长度
{
    length=l;
}
   void Rectangle::setWidth(int w) //设置矩形的宽度
{
     width=w;
}
   int Rectangle::getArea()   //计算并返回矩形的面积
{
     return width*length;
}

 

  • 4
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
PTA(Programming Teaching Assistant)是一个在线编程练习平台,用于帮助学生提高编程能力。在PTA上,有一个关于计算图形面积的题目,涉及到抽象使用。 抽象是一种特殊的,不能被实例化,只能被继承。在计算图形面积的题目中,可以定义一个抽象Shape,其中包含一个纯虚函数getArea(),用于计算图形的面积。具体的图形(如圆、矩形、三角形等)可以继承Shape,并实现自己的getArea()函数。 以下是一个示例代码: ```cpp #include <iostream> using namespace std; // 抽象 Shape class Shape { public: virtual double getArea() = 0; // 纯虚函数 }; // 圆 Circle class Circle : public Shape { private: double radius; public: Circle(double r) : radius(r) {} double getArea() { return 3.14 * radius * radius; } }; // 矩形 Rectangle class Rectangle : public Shape { private: double width; double height; public: Rectangle(double w, double h) : width(w), height(h) {} double getArea() { return width * height; } }; // 三角形 Triangle class Triangle : public Shape { private: double base; double height; public: Triangle(double b, double h) : base(b), height(h) {} double getArea() { return 0.5 * base * height; } }; int main() { Shape* shape1 = new Circle(5); Shape* shape2 = new Rectangle(4, 6); Shape* shape3 = new Triangle(3, 4); cout << "圆的面积:" << shape1->getArea() << endl; cout << "矩形面积:" << shape2->getArea() << endl; cout << "三角形的面积:" << shape3->getArea() << endl; delete shape1; delete shape2; delete shape3; return 0; } ``` 在上述代码中,定义了一个抽象Shape,以及三个具体的图形Circle、Rectangle和Triangle。每个图形都实现了自己的getArea()函数来计算面积。在main函数中,创建了不同型的图形对象,并通过基指针调用各自的getArea()函数来计算并输出面积
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值