2015-05-09 70 views
1

我在我们的家庭作业中使用类来做锥体的计算。我很困惑如何正确使用类来定义私有成员的半径和高度,然后使用这些(由用户输入)来进行计算。我在哪里使用类时出错?

#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; 
} 
+2

你必须定义一些设置或获取功能,在您的私人mebers设定值,你不能将值直接从main分配给私有成员。 – Tejendra

+1

,如果你想得到由私人成员计算的SurfaceArea和Volume,你不应该把它作为参数。 – Tejendra

回答

3

的想法是,你构建一个带有一个预定义的R,H锥保存这些断成私有变量(这些是固定的圆锥体的寿命圆锥的性质)

之后,VolumeSurfaceArea不需要参数 - 它们可以处理私有变量的值。

因此,像这样:

#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; 
} 
+0

问题是我需要用户输入他们自己的'r'和'h'的值... – snoopdawoop

+0

您可以放回代码。像你一样接受输入,然后将其作为参数传递给构造函数 –

0

的想法是,你让用户输入的值,那么你创建(私有)成员变量与值的对象​​,其创建的实例会记住(存储),然后查询计算结果的对象。对象应该封装逻辑(公式)来计算表面积,但不应该决定如何处理它(输出到cout或其他)。因此

你的主要功能应该是这样的:

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; 
} 

现在结合起来,与对方的回答:)