current position:Home>How should this program be completed

How should this program be completed

2022-02-03 01:07:50 CSDN Q & A

12.2、 Declare a base class OBJ, The base class protects members m_Name, The derived classes of cube and sphere are CUBE and SPHERE, The members of the cube are side lengths m_R, The members of the sphere are radii m_Radial, Initialize a cube and sphere object in the program , And set the cube side length to 3.2, The sphere radius is set to 3.5, And use the pointer of the base class , By dynamically binding objects to the previous cube and sphere , Use this base class pointer to access and output the volume of the cube and sphere .

Refer to the answer 1:
#include <iostream>#include <cmath>#include <stdexcept>#include <memory>class OBJ{public:    OBJ(const std::string &name) : m_Name(name) {}    virtual ~OBJ() = default;    virtual float volume() const = 0;    const std::string getName() const { return m_Name; }    void setName(const std::string &name) { m_Name = name; }protected:    std::string m_Name;};class CUBE : public OBJ{public:    CUBE(const std::string &name, float r) : OBJ(name), m_R(r)    {        if (r <= 0.0f)            throw std::invalid_argument("invalid cube");    }    float getR() const { return m_R; }    void setR(float r) { m_R = r; }    virtual float volume() const { return std::pow(m_R, 3); }private:    float m_R;};class SPHERE : public OBJ{public:    SPHERE(const std::string &name, float r) : OBJ(name), m_Radial(r)    {        if (r <= 0.0f)            throw std::invalid_argument("invalid sphere");    }    float getRadial() const { return m_Radial; }    void setRadial(float r) { m_Radial = r; }    virtual float volume() const { return static_cast<float>(std::pow(m_Radial, 3) * M_PI * 4.0 / 3.0); }private:    float m_Radial;};int main(){    OBJ *p1 = new CUBE("cube1", 3.2f);    OBJ *p2 = new SPHERE("sphere1", 3.5f);    std::cout << p1->getName() << "'s volume is " << p1->volume() << '\n';    std::cout << p2->getName() << "'s volume is " << p2->volume() << '\n';    delete p1;    delete p2;    return 0;}

Refer to the answer 2:

copyright notice
author[CSDN Q & A],Please bring the original link to reprint, thank you.

Random recommended