gpt4 book ai didi

c++ - 程序错误;需要建议

转载 作者:行者123 更新时间:2023-11-28 05:40:24 24 4
gpt4 key购买 nike

通常我有一个名为“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: NamePlease enter person's weight: 123Please enter person's height: 123More data? (y/n) nThe person with maximum BMI (body mass index) isWeight: 1.7881e-307Height: 2.0746e-317

最佳答案

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

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

或更好:

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

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

关于c++ - 程序错误;需要建议,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37240365/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com