【PTA】立方体类

定义立方体类Box,数据成员有长宽高且都是整数,构造函数初始化数据成员,成员函数计算体积,主函数中输入长宽高,输出立方体体积。

输入格式:

输入立方体的长宽高,中间用空格分隔。

输出格式:

输出体积并换行。

样例">输入样例:

1 2 3

输出样例:

6

#include <iostream>

using namespace std;
class Box
{
    private:
    int length;
    int wide;
    int high;
    int volume;
    public:
        void input()
        {
            cin>>length>>wide>>high;
        }
        void output()
        {
            volume=length*wide*high;
            cout<<volume<<endl;
        }
        Box()
        {
        length=0;
        wide=0;
        high=0;
        volume=0;
        }
};
int main()
{
    Box date1;
    date1.input();
    date1.output();
    return 0;
}

 

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 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、付费专栏及课程。

余额充值