当将freeSeats设置为0时,我的代码仍然说一个人在他/她的汽车中有可用座位。

我创建了两个类。一种用于汽车,一种用于人。 Car 类有一个功能,可以查看车内是否有空闲座位。一个人-对象可以有一辆汽车。在检查此人是否有可用座位时,即使我输入“0”,我的代码也会响应"is"。为什么?

#pragma once
#include <iostream>

//Here is class Car declaration
class Car {
private:
    unsigned int freeSeats;
public:
    bool hasFreeSeats() const;
    void reserveFreeSeat();
    Car( unsigned int freeSeats);

};


//Here is function definition
#include "Car.h"

bool Car::hasFreeSeats() const {
    if (freeSeats > 0)
        return true;
    return false;
}

void Car::reserveFreeSeat() {
    --freeSeats;
}

Car::Car(unsigned int freeSeas) :
    freeSeats{ freeSeats }
{
}


//Here is class Person declaration

class Person {
private:
    std::string name;
    std::string email;
    Car *car; //pointer to a car
public:
    Person(std::string name, std::string email, Car *car = nullptr);
    std::string getName() const;
    std::string getEmail() const;
    void setEmail();
    bool hasAvalibaleSeats() const;
    friend std::ostream& operator << (std::ostream& os, const Person& p);
};

//Here is function definition


Person::Person(std::string name, std::string email, Car *car) :
    name{ name }, email{ email }, car{ car }
{
}

std::string Person::getName() const {
    return name;
}

std::string Person::getEmail() const {
    return email;
}

void Person::setEmail() {
    std::string newEmail;
    std::cout << "What is the e-mail adress?";
    std::cin >> newEmail;
    email = newEmail;
    std::cout << "E-mail has been set." << std::endl;
}


bool Person::hasAvalibaleSeats() const {
    if (car != nullptr) { //check if there is a car
        return car->hasFreeSeats();
    }
    return false;
}



std::ostream& operator << (std::ostream& os, const Person& p) {
    std::string seats = "No";
    if (p.hasAvalibaleSeats())
        seats = "Yes";
    return os << "Name: " << p.name << "\nE-mail: " << p.email << "\nHas free seats: " << seats << std::endl;
}

//From main im calling
#include "Car.h"
#include "Person.h"

int main() {
    Car ferrari{ 2 };
    Car bugatti{ 3 };
    Car jeep{0};


    Person one{ "Aleksander","[email protected]", &ferrari };
    Person two{ "Sara","[email protected]", &bugatti };
    Person three{ "Daniel", "[email protected]", &jeep };
    Person four{ "Chris", "[email protected]" };

    std::cout << one << std::endl;
    std::cout << two << std::endl;
    std::cout << three << std::endl;
    std::cout << four << std::endl;
    system("pause");
    return 0;
}

我得到

姓名:亚历山大
电子邮箱:[email protected]
有空位:是

姓名:萨拉
电子邮箱:[email protected]
有空位:是

姓名:丹尼尔
电子邮箱:[email protected]
有空位:是

姓名:克里斯
电子邮箱:[email protected]
有空位:否

但我希望丹尼尔有空闲座位是“不”

最佳答案

这里有一个错字:

Car::Car(unsigned int freeSeas) :
    freeSeats{ freeSeats }
    {}

您编写的是freeSeas而不是freeSeats。因此,freeSeas参数未使用,并且freeSeats{ freeSeats }不执行任何操作,因为freeSeats引用成员变量,而不是参数。

关于c++ - 为什么我的代码应该说 "Yes"时说 "No"?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58394224/

10-11 21:01