如果还有关于布尔的声明C++

If else statement on bool in C++

本文关键字:声明 C++ 于布尔 如果      更新时间:2023-10-16

基本上,我有3个函数第一个和第二个功能是检查点火是真是假。第三个功能基本上是检查点火是否开启,速度不能大于65,如果速度大于65,它将"修复"该速度为65。然而,如果点火开关关闭,速度将为 0。

然而在我的代码中,我做了一个 if else 语句。当我打印关闭点火的部分时,我得到的值是 65。它假设为 0。

我可以知道我的代码出了什么问题吗?

车.H

#ifndef car_inc_h
#define car_inc_h
#include <iostream>
#include <string>
using namespace std;
class Car {
    bool isIgnitionOn;
    int speed;
public:
    void turnIgnitionOn();
    void turnIgnitionOff();
    void setSpeed(int);
    void showCar();
};
#endif

车.cpp

#include <iostream>
#include <string>
#include "Car.h"
using namespace std;
void Car::turnIgnitionOn() {
    this->isIgnitionOn = true;
}
void Car::turnIgnitionOff() {
    this->isIgnitionOn = false;
};

void Car::setSpeed(int speed) {
    if (isIgnitionOn == true) {
        if (speed >= 65) {
            this->speed = 65;
        }
        else {
            this->speed = speed;
        }
    }
    else if (isIgnitionOn == false){
        this->speed = 0;
    }
};

void Car::showCar() {
    if (isIgnitionOn == true) {
        cout << "Ignition is on." << endl;
        cout << "Speed is " << speed << endl;
    }
    else if (isIgnitionOn == false) {
        cout << "Ignition is off" << endl;
        cout << "Speed is " << speed << endl;
    }

};

主.cpp

#include <iostream>
#include <string>
#include "Car.h"
using namespace std;
int main() {
    Car myCar;
myCar.turnIgnitionOn();
    myCar.setSpeed(35);
    myCar.showCar();
    myCar.setSpeed(70);
    myCar.showCar();
    myCar.turnIgnitionOff();
    myCar.showCar();
    return 0; 
}
speed永远不会

重置为 0。您可以在turnIgnitionOff中添加this->speed=0毕竟更合乎逻辑。