Domanda

So I'm making a program that reads info from a file in the format of:

20 6
22 7
15 9

The program reads these as an Event where the first number is time and the second is length and must add events to the queue in the EventList struct. Currently I am getting an a compilation error in the EventList::fill function saying I have undefined reference to Event::Event.

My question is how to properly define a new Event in the EventList::fill function so that I can ultimately push these Events into the priority queue defined in EventList? I am confused by the way Event's constructor is set up and how to properly initialize the variables of it so that the program can read each line of the file and make an event with the proper values.

Here is what I have so far:

#include <fstream>
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <queue>

using namespace std;

struct Event {
enum EventKind {Arrival, Departure};
EventKind type;
int time, length;

Event (EventKind theType=Arrival, int theTime=0, int theLength=0);
};

istream& operator>>(istream& is, Event& e);

typedef priority_queue<Event> EventPQType; 

struct EventList {
    EventPQType eventListPQ;
    void fill(istream& is);
};

int main(int argc, char** argv)
{
   EventList eventList;

   char* progname = argv[0];  
   ifstream ifs(argv[1]);
   if (!ifs) {
       cerr << progname << ": couldn't open " << argv[1] << endl;
       return 1;
   }
   eventList.fill(ifs);
}

void EventList::fill(istream& is) {
Event e;

while(is >> e){
    cout << e.time << e.length; 
}

cout << "EventList::fill was called\n";
 }

istream& operator>>(istream &is, Event &e) {
is >> e.time >> e.length;
return is;
}
È stato utile?

Soluzione

As mentioned in other answers, you need to provide a constructor:

struct Event {
  enum EventKind {Arrival, Departure};
  EventKind type;
  int time, length;

  Event(EventKind theType=Arrival, int theTime=0, int theLength=0);
};

Event::Event(EventKind theType, int theTime, int theLength):
  type(theType),
  time(theTime),
  length(theLength)
{}

It is also possible to inline the definition inside the declaration of your structure:

struct Event {
  enum EventKind {Arrival, Departure};
  EventKind type;
  int time, length;

  Event(EventKind theType=Arrival, int theTime=0, int theLength=0):
    type(theType),
    time(theTime),
    length(theLength)
  {}
};

In fact, in C++, it is possible to think about structures like classes whose members are public by default. Hence, the way to define a constructor is the same for structures and classes.

Altri suggerimenti

You need to provide a definition for the constructor.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top