程序错误;需要建议

时间:2016-05-15 15:50:13

标签: c++

一般来说,我有一个名为" person"及其方法,print:打印数据,is_better_than查找一些最大数字。我无法理解这是什么问题。有什么建议?

#include <iostream>
#include <string>
#include <math.h>
using namespace std;

class person
{
    private:
        string name;
        double weight;
        double height;

    public:
        person(); //Constructor

        bool is_better_than(person best);
        void read();
        void print();

        void operator=(const person& b); //overloading operator
};

person::person()
 {
    string name = "";
    double weight = 0;
    double height = 0;
 }

 void person::print()
{
    cout << name << "\nWeight: " << weight << "\nHeight: " << height << "\n";
}

void person::read()
{
    cout << "Please enter person's name: ";
    getline(cin, this->name);
    cout << "Please enter person's weight: ";
    cin >> this->weight;
    cout << "Please enter person's height: ";
    cin >> this->height;

    string remainder;
    getline(cin, remainder); //clear the buffer
}

bool person::is_better_than(person best)
{
    if ((this->weight / pow(this->height,2) >= best.weight / (pow(best.height,2))) || best.weight == 0)
        return true;

    return false;
}

// iperfortosi telesti =
void person::operator=(const person & b)
{
    this->name = b.name;
    this->weight = b.weight;
    this->height = b.height;
}

int main()
{
    person maxBMI;
    bool cont = true;
    while (cont)
    {
        person newperson;
        newperson.read();

        if (newperson.is_better_than(maxBMI))
            maxBMI = newperson;

        cout << "More data? (y/n) ";
        string answer;
        getline(cin, answer);

        if (answer != "y")
            cont = false;
    }
    cout << "The person with maximum BMI (body mass index) is ";
    maxBMI.print();
    return 0;
}

输出:

Please enter person's name: Name
Please enter person's weight: 123
Please enter person's height: 123
More data? (y/n) n
The person with maximum BMI (body mass index) is
Weight: 1.7881e-307
Height: 2.0746e-317

1 个答案:

答案 0 :(得分:1)

您的默认构造函数不起作用,因为它分配给局部变量而不是类变量。它应该是这样的:

person::person()
{
    name = "";
    weight = 0;
    height = 0;
}

或更好:

person::person() : name(""), weight(0.0), height(0.0) {}

使用默认构造函数,类属性保持未初始化,并且best.weight最初为零的假设不起作用。