以下是代码实现:

#include <iostream>
#include <cmath>

using namespace std;

class Shape {
public:
    virtual double calculateArea() = 0;
    virtual double calculateVolume() = 0;
};

class Box : public Shape {
private:
    double length, width, height;
public:
    Box(double l, double w, double h) : length(l), width(w), height(h) {}
    double calculateArea() {
        return 2 * (length * width + width * height + height * length);
    }
    double calculateVolume() {
        return length * width * height;
    }
};

class Sphere : public Shape {
private:
    double radius;
public:
    Sphere(double r) : radius(r) {}
    double calculateArea() {
        return 4 * M_PI * radius * radius;
    }
    double calculateVolume() {
        return 4.0 / 3.0 * M_PI * pow(radius, 3);
    }
};

void printAreaAndVolume(Shape* shape) {
    cout << "Area: " << shape->calculateArea() << endl;
    cout << "Volume: " << shape->calculateVolume() << endl;
}

int main() {
    Box box(2, 3, 4);
    Sphere sphere(5);

    cout << "Box:" << endl;
    printAreaAndVolume(&box);

    cout << "Sphere:" << endl;
    printAreaAndVolume(&sphere);

    return 0;
}

在这个程序中,我们定义了一个抽象类 Shape,其中包含了两个纯虚函数 calculateArea()calculateVolume(),用于计算形状的面积和体积。我们还定义了两个具体的子类 BoxSphere,分别表示长方体和球。

Box 类中,我们定义了三个属性 lengthwidthheight,并实现了父类中的两个纯虚函数。在 Sphere 类中,我们定义了一个属性 radius,并同样实现了父类中的两个纯虚函数。

main() 函数中,我们创建了一个 Box 对象和一个 Sphere 对象,并分别调用了 printAreaAndVolume() 函数来计算它们的面积和体积。这个函数接受一个 Shape 类型的指针作为参数,因此可以计算任何形状类对象的面积和体积。

请使用面向对象编程思想用cpp简单编写代码实现如下功能验证继承的多根性和抽象类等技能点。 Shape形状类有面积和体积两个属性和计算面积、计算体积两个虚方法;Box长方形类是形状类中的一种特有长、宽和高属性;Sphere球类特有半径属性。编写独立的函数实现计算任何形状类对象的面积和体积的功能。你给的程序里的M_PI好像未定义

原文地址: https://www.cveoy.top/t/topic/b4JS 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录