簡體   English   中英

如何在C ++中正確初始化Struct對象

[英]How to properly initialize Struct object in c++

因此,我正在編寫一個程序,該程序以以下格式從文件讀取信息:

20 6
22 7
15 9

程序將它們讀取為一個Event,其中第一個數字是時間,第二個數字是長度,必須將事件添加到EventList結構的隊列中。 目前,我在EventList :: fill函數中遇到編譯錯誤,說我對Event :: Event有未定義的引用。

我的問題是如何在EventList :: fill函數中正確定義一個新事件,以便最終將這些事件推送到EventList中定義的優先級隊列中? 我對Event的構造函數的設置方式以及如何正確初始化其變量的方法感到困惑,以便程序可以讀取文件的每一行並使用適當的值創建事件。

這是我到目前為止的內容:

#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;
}

您需要為構造函數提供一個定義。

如其他答案所述,您需要提供一個構造函數:

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)
{}

也可以在結構的聲明中內聯定義:

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)
  {}
};

實際上,在C ++中,可以考慮默認情況下成員為公共的類之類的結構。 因此,對於結構和類,定義構造函數的方式是相同的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM