简体   繁体   中英

Using vector of a class that contains static member variable

I had an Airplane class and this Airplane had a vector of Seat class named "m_seat". In the Constructor of my Airplane, I used the number of seats as the needed parameter to resize the m_seat vector size to the requested size of the user. This was my code:

class Seat;

class Airplane {
    vector<Seat> m_seat;
public:
    Airplane(int);
};

class Seat{
    static int m_seatNumber;
public:
    Seat() { m_seatNumber += 10; }
};

int Seat::m_seatNumber = 100;

Airplane::Airplane(int numberOfSeats) {
    for (int i = 0; i<numberOfSeats; ++i) {
        m_seat.push_back();
    }
}

int main()
{
    Airplane(80);
    return 0;
}

But it gave this error.

std::vector<_Ty,_Aloc>::push_back no overload of function takes 0 arguments,

and if this was really the problem, I had no idea what should I have put in my push_back()? So I tried {}

m_seat.push_back({});

and It worked!

Now, I have another problem which is my main problem (SO rule: Ask only one question at a time!) that all seat numbers appear to be increased to the same number! I also used the "resize" member function of the vector, instead of that loop:

m_seat.resize(numberOfSeats);

But the problem (same increase in the number of the m_seatNumber) remains unsolved. Non-native English Speaker, Sorry.

Disclaimer: This is a "best guess" answer.

If you wanted each seat to have a different, automatically increasing number, you need two values; one non-static, describing each seat, and one static, describing last-used number:

class Seat{
    static int lastSeatNumber;
    int seatNumber;

public:
    Seat() { seatNumber = lastSeatNumber; lastSeatNumber += 10; }
};
int Seat::lastSeatNumber = 100;

That way each seat will receive its distinct number. This design is bad, however, as it doesn't allow eg seat number sharing between two airplanes! It also doesn't allow you to "free up" the numbers of seats you're no longer using, and the number can only keep growing. Also copying a Seat , while possible, won't manipulate that number at all. It'd be much better to allow the Airplane class to assign the seat numbers:

class Seat{
    int seatNumber;

public:
    Seat(int seatNumber) : seatNumber(seatNumber) { }
};

Airplane::Airplane(int numberOfSeats) {
    int seatNumber = 100;
    const int numberIncrement = 10;

    for (int i = 0; i < numberOfSeats; ++i) {
        m_seat.push_back(Seat(seatNumber));
        seatNumber += numberIncrement;
    }
}

This way you can get the old behavior by adding another parameter to the airplane constructor telling it which number to start counting from.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM