我在使用课程时哪里出错了?

时间:2015-05-09 09:29:53

标签: c++ class object

我在家庭作业中使用课程来进行锥形计算。我很困惑如何正确使用类来定义私有成员为半径和高度,然后使用它们(由用户输入)进行计算。

#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 个答案:

答案 0 :(得分:3)

这个想法是你构造一个带有预定义r,h的锥体,并将它们保存到私有变量中(这些是在锥体的生命周期内固定的锥体属性)

之后"SELECT * FROM User WHERE LOWER(bname) = LOWER(@0)" Volume不需要参数 - 它们可以处理私有变量的值。

这样的事情:

SurfaceArea

答案 1 :(得分: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;
}

现在将其与其他答案结合起来:))