Reputation: 19
I am using classes in our homework assignment to do calculations for a cone. I am confused on how to properly use classes to define the private members to be radius and height and then use those (as entered by the user) to do calculations.
#include <iostream>
#include <cmath>
#include <string>
using namespace std;
class cone
{
private:
double r, h;
public:
void SurfaceArea(double r, double h)
{
double S = M_PI * r * (r + pow((pow(h, 2.0) + pow(r, 2.0)), 0.5));
cout << "Surface Area: " << S << endl;
}
void Volume(double r, double h)
{
double V = M_PI * h / 3.0 * pow(r, 2.0);
cout << "Volume: " << V << endl;
}
};
int main()
{
cone green;
cout << "Enter radius: " << endl;
cin >> r;
cout << "Enter height: " << endl;
cin >> h;
green.SurfaceArea(r, h);
green.Volume(r, h);
cout << "1. Recalculate\n2. Main Menu\n3. Quit\n";
cin >> option;
return 0;
}
Upvotes: 1
Views: 61
Reputation: 56863
The idea is that you let the user enter the values, then you create an object with those values which the created instance will remember (store in (private) member variables) and then query the object for the result of the calculations. The object should encapsulate the logic (formula) to calculate a surface area, but it should not decide what to do with it (output to cout
or whatever).
Your main function should therefore look like this:
int main()
{
double r, h;
cout << "Enter radius: " << endl;
cin >> r;
cout << "Enter height: " << endl;
cin >> h;
// create an object with the entered values.
cone green( r, h );
// query the object for the calculated values
// without providing r and h again - the object
// should know/remember those values from above.
cout << green.SurfaceArea() << endl;
cout << green.Volume() << endl;
return 0;
}
Now combine that with the other answer :)
Upvotes: 0
Reputation: 1986
The idea is that you construct a cone that comes with a predefined r, h and save these off into private variables (these are properties of the cone that are fixed for the lifetime of the cone)
After that Volume
and SurfaceArea
don't need to take arguments -- they can work off of the values of the private variables.
So something like this:
#include <iostream>
#include <cmath>
using namespace std;
class Cone
{
double _r, _h;
public:
Cone(double r, double h) : _r(r), _h(h) { }
double SurfaceArea() {
return M_PI*_r*(_r+pow((pow(_h, 2.0)+pow(_r, 2.0)),0.5));
}
double Volume() {
return M_PI*_h/3.0*pow(_r, 2.0);
}
};
int main()
{
Cone green(1,2);
cout << green.SurfaceArea();
return 0;
}
Upvotes: 3