繁体   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