Using a .h and .cpp file, implement a Sphere class with the following data field
ID: 3683806 • Letter: U
Question
Using a .h and .cpp file, implement a Sphere class with the following data fields and methods.
Constant
Use the following value for PI = 3.14159
Data
radius: double
color: string
MethodsSphere() - default constructor
should set the radius to one and color to green
Sphere(double r) - custom constructor
sets the radius to r and color to green
Sphere(double r, string c) - custom constructor
sets the radius to r and color to c
void setRadius( double)
mutator method used to change the radius
double getRadius() const
constant function that return the radius
void setColor(string)
mutator method to set the color of the Sphere
string getColor() const
constant accessor method that return the color of the Sphere
double area() const
constant function that returns the surface area of the Sphere
double volume() const
constant function that returns the volume of the Sphere
bool isEqual(const Sphere other) const
constant boolean function that return TRUE is two Spheres have the same radius and color, FALSE otherwise.
Explanation / Answer
#include "header.h"
#include <iostream>
#define pi 3.14159
using namespace std;
class Sphere
{
private :
double radius;
string color;
public:
Sphere()
{
radius=1;
color="green";
}
Sphere(double r)
{
radius=r;
}
Sphere(double r,string c)
{
radius=r;color=c;
}
void setRadius(double r)
{
radius=r;
}
double getRadius() const
{
return radius;
}
void setColor(string c)
{
color=c;
}
string getColor() const
{
return color;
}
bool isEqual(const Sphere one,const Sphere two) const
{
if(one.radius==two.radius && one.color==two.color)
return true;
else
return false;
}
double area(double r) const
{
return (4*pi*r*r);
}
double volume(double r) const
{
return (4/3*pi*r*r*r);
}
};
int main()
{
Sphere s;
cout << " Radius :" <<s.getRadius();
cout << " Color :" << s.getColor();
cout << " Surface area :" << s.area(s.getRadius());
cout << " Volume :" << s.volume(s.getRadius());
Sphere s1=2;
Sphere s2=1;
cout << " ";
s2.setColor("green");
s1.setColor("red");
cout << " Radius :" <<s1.getRadius();
cout << " Color :" << s1.getColor();
cout << " Surface area :" << s1.area(s1.getRadius());
cout << " Volume :" << s1.volume(s1.getRadius());
cout << " s and s2 Objects are :"<<s.isEqual(s2,s) << " ";
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.