You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++类成员变量与成员函数输出错误数值是什么原因?

问题根因

你出错的核心原因是错误创建了4个独立的Auto类实例,类的每个实例的成员变量都是互相独立的,你给不同实例分别设置了车型、里程、油耗参数,最后调用输出方法的是完全没设置过任何参数的outputFunction实例,它的成员变量都是未初始化的内存垃圾值,自然会输出乱码甚至异常数值。

修正方案

只需要创建1个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 << " gallons of gas" << endl;
        cout << "This car gets " << calculateMilesPerGallon(milesDriven, gallonsOfGas) << " mpg.";
    }
};


int main()
{
    // 仅创建1个Auto实例即可
    Auto myCar;
    string carModel = "Toyota Camry";
    int carMiles = 100;
    double carGallons = 10;
    
    // 所有操作都在同一个实例上执行
    myCar.setModel(carModel);
    myCar.setMilesDriven(carMiles);
    myCar.setGallonsOfGas(carGallons);
    myCar.output();
    
    return 0;
}

运行后即可输出你预期的结果。

内容的提问来源于stack exchange,提问作者wawa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 11:45:04