2017-10-09 41 views
1

有人可以告诉我,为什么我在该代码中出现了段错误?我不知道这是为什么。我使用代码:块但在线编译器也有同样的问题。我不知道问题出在哪里。类内部的C++队列,分段错误

#include <iostream> 
#include <queue> 
#include <memory> 

using namespace std; 

class Task { 
private: 
    queue <string> q; 
    public: 
    string input; 
    void read (int hm) 
    { 
     for (int i=1;i<=hm;i++) 
     { 
      cin>>input; 
      q.push(input); 
     } 
    } 
    void count() 
    { 
     cout<<q.back(); 
    } 
}; 

int main() 
{ 
    unique_ptr <Task> ptr; 

    int how_many; 
    cin>>how_many; 
    ptr->read(how_many); 
    ptr->count(); 
    return 0; 
} 

回答

3

指针ptr正在被使用而未被初始化。使用:

std::unique_ptr<Task> ptr = std::make_unique<Task>(); 

也就是说你还应该明确包含<string>头。

+1

谢谢!容易的错误:) – Michal123

+0

而你的'count()'将返回最近元素的值而不是元素的数量。为此,请使用'q.size()'。例如:http://www.cplusplus.com/reference/queue/queue/size/ –