月落渐霜 2023-07-05 15:23 采纳率: 88.5%
浏览 24
已结题

c++设计基类为抽象类派生体积类

设计一个基类 Object 为抽象类,有一个纯虚函数 float volume()计算体积。另外
由 Object 派生两个类 Cuboid 和 Cylinder。Cuboid 类用于表示长方体,包含长 length、
宽 width、高 high 信息。Cylinder 类用于表示圆柱体,包含半径 radius 和高 high 信
息。设计类使得下列主函数能够正确执行。

void main() 
{ Cuboid cu(3,4,5); 
 Cylinder cy(4,10); 
 Object ptr[2]={&cu,&cy}; 
 cout<<"总体积:"<<ptr[0]->volume()+ptr[1]->volume()<<endl; 
} 

  • 写回答

2条回答 默认 最新

  • threenewbee 2023-07-05 15:25
    关注
    #include <iostream>
    using namespace std;
    
    // 抽象基类 Object
    class Object {
    public:
        virtual float volume() const = 0; // 纯虚函数
    };
    
    // 派生类 Cuboid
    class Cuboid : public Object {
    private:
        float length;
        float width;
        float height;
    public:
        Cuboid(float l, float w, float h) : length(l), width(w), height(h) {}
        float volume() const {
            return length * width * height;
        }
    };
    
    // 派生类 Cylinder
    class Cylinder : public Object {
    private:
        float radius;
        float height;
    public:
        Cylinder(float r, float h) : radius(r), height(h) {}
        float volume() const {
            return 3.14159 * radius * radius * height;
        }
    };
    
    int main() {
        Cuboid cu(3, 4, 5);
        Cylinder cy(4, 10);
        Object* ptr[2] = {&cu, &cy};
        cout << "总体积: " << ptr[0]->volume() + ptr[1]->volume() << endl;
        return 0;
    }
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 7月13日
  • 已采纳回答 7月5日
  • 创建了问题 7月5日