【发布时间】:2021-12-21 16:00:24
【问题描述】:
我正在学习如何在 C++ 中使用类。现在我正在开发一个小程序,它应该根据给定的英里数和加仑数显示车辆的每加仑英里数。分配说要在主函数中调用成员函数,以便在 Auto 类中设置成员变量。这是我的代码:
#include <iostream>
using namespace std;
class Auto {
public:
string model;
int milesDriven;
double gallonsOfGas;
double calculateMilesPerGallon(int milesDriven, double gallonsOfGas) {
return milesDriven / gallonsOfGas;
}
void setModel(string newModel){
model = newModel;
}
void setMilesDriven(int newMiles){
milesDriven = newMiles;
}
void setGallonsOfGas(double newGallons){
gallonsOfGas = newGallons;
}
void output(){
cout << "A " << model << " was driven " << milesDriven << " miles, and used " << gallonsOfGas << endl;
cout << "This car gets " << calculateMilesPerGallon(milesDriven, gallonsOfGas) << "mpg.";
}
};
int main()
{
Auto modelFunction;
Auto milesFunction;
Auto gasFunction;
Auto outputFunction;
string carModel = "Toyota Camry";
int carMiles = 100;
double carGallons = 10;
modelFunction.setModel(carModel);
milesFunction.setMilesDriven(carMiles);
gasFunction.setGallonsOfGas(carGallons);
outputFunction.output();
return 0;
}
它应该显示类似“一辆丰田凯美瑞的车开了 100 英里,用了 10 加仑汽油,每加仑跑了 10 英里”。相反,我的输出显示“A 行驶了 -1538932792 英里,使用了 4.66265e-310 这辆车得到-infmpg。”我在做什么导致输出是这样的?我刚开始使用类,所以我对它们没有太多经验。谢谢你的建议。
【问题讨论】:
-
您有四个不同的
Auto对象,每个对象都有自己的成员变量(model等)。为此,您只需要一个Auto。 -
不要为类成员变量使用相同的名称和函数的参数名称。它总是会引起混乱,并不总是会产生正确的代码。
-
除了上述建议之外,还建议为您的类定义一个构造函数,将所有 POD 类型(plain-old-data,eg int 和 double)初始化为一个合理的默认值。
0的值通常是一个不错的选择。正如所写,这些是未初始化的值,调用者应该明确地初始化它们。