【问题标题】:How to properly initialize Struct object in c++如何在 C++ 中正确初始化 Struct 对象
【发布时间】:2014-05-11 22:10:25
【问题描述】:

所以我正在制作一个程序,它以以下格式从文件中读取信息:

20 6
22 7
15 9

程序将这些作为事件读取,其中第一个数字是时间,第二个是长度,并且必须将事件添加到 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;
}

【问题讨论】:

  • 到底是什么问题?
  • 看起来你所缺少的只是将它排入队列。
  • 问题是“事件 e;”在我的填充函数中导致编译错误,说我对 Event::Event 有未定义的引用。如何正确定义一个新事件,以便我可以开始将它们添加到 EventList 中的队列中
  • 哦,定义(实现)构造函数。你只是声明了它。
  • 这就是我一直在尝试的,但由于它的设置方式,我不确定如何正确实施它。我希望每个事件的事件类型到达,并且填充函数只需将文件中的值写入事件时间和长度变量

标签: c++ struct queue


【解决方案1】:

正如其他答案中提到的,您需要提供一个构造函数:

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++ 中,可以考虑像类这样的结构,其成员默认是公共的。因此,定义构造函数的方式对于结构体和类是相同的。

【讨论】:

    【解决方案2】:

    您需要为构造函数提供定义。

    【讨论】:

    • 我理解这一点,但我的问题是如何以构造函数现在的样子正确地做到这一点?我知道这是一个愚蠢的问题,但我对如何使用当前构造函数正确定义新事件感到非常困惑。
    猜你喜欢
    • 1970-01-01
    • 2022-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多