Data “member not declared in this scope”

2019-09-19 09:08发布

问题:

I'm trying to create a vector which will store objects. I have added to the header file of the class as a private data member.

I am trying to initialize this vector as being empty (so that I can add objects to it later on in the program) but when I compile this program to test, this error is returned:

...error: '_bookingVector' was not declared in this scope|

I think the problem is with my initialization list on my default constructor(_bookingVector is obviously the vector):

Schedule::Schedule() : _bookingVector()
{ }

Is my syntax wrong? Or are vectors initialized differently?

Here is my code:

Schedule.h

#ifndef SCHEDULE_H
#define SCHEDULE_H
#include "Booking.h"
#include <vector>    
using namespace std;


class Schedule
{    
    public:
        Schedule();
        void AddBooking(int bday, int btime, int btrainer, int bid);
        void RemoveBooking(int bday, int btime);
        void DisplaySchedule();
        void DisplayAvailableTimeSlots();    
        //For Testing
        void DisplayDebug();

    private:
        vector<Booking> _bookingVector;   

};    
#endif // SCHEDULE_H

Schedule.cpp

#include "Schedule.h"
#include "Booking.h"
#include <vector>
#include <iostream> 

Schedule::Schedule() : _bookingVector()
{ }    

void AddBooking(int bday, int btime, int btrainer, int bid){    
    Booking bookingObject(bday, btime, btrainer, bid);
    _bookingVector.push_back(bookingObject);    

}


void DisplayDebug(){

    for(int i = 0; i < _bookingVector.size(); ++i){    
        cout << _bookingVecotr[i] << endl;    
    }    
}

I'm very eager to learn what I'm doing wrong and fix it.

回答1:

The issue is not with the constructor, which looks fine if unnecessary1. The issue is that you have defined AddBooking and DisplayDebug as non-member functions, but these should be members in order to access other members of the class.

Modify the definitions to be in the scope of the Schedule class thus:

void Schedule::AddBooking(int bday, int btime, int btrainer, int bid) { ...
     ^^^^^^^^^^

void Schedule::DisplayDebug(){ ...
     ^^^^^^^^^^

Also, don't say using namespace std in a header file (I'd go further and say don't say it anywhere but there isn't universal agreement on that.)


1 Your default constructor does not do anything that the compiler-generated one wouldn't do. You can safely remove it.