Вставка в мультикарту вызывает segfault - PullRequest
0 голосов
/ 12 апреля 2011

Я работаю над проектом, использующим мультикарты внутри своего класса, и столкнулся с segfault.Вот части моего кода, касающиеся этой проблемы.Я был бы очень признателен за помощь.Спасибо.

Вот файл database.h

#include <iostream>
#include <map>

using namespace std;

class database{
 public:
  database(); // start up the database                                               
  int update(string,int); // update it                                               
  bool is_word(string); //advises if the word is a word                              
  double prox_mean(string); // finds the average prox                                
 private:
  multimap<string,int> *data; // must be pointer                                     
 protected:

};

Вот база данных.cpp

#include <iostream>
#include <string>
#include <map>
#include <utility>

#include "database.h"

using namespace std;


// start with the constructor                                               
database::database()
{
  data = new multimap<string,int>; // allocates new space for the database  
}

int database::update(string word,int prox)
{
  // add another instance of the word to the database                       
  cout << "test1"<<endl;
  data->insert( pair<string,int>(word,prox));
  cout << "test2" <<endl;
  // need to be able to tell if it is a word                                
  bool isWord = database::is_word(word);
  // find the average proximity                                             
  double ave = database::prox_mean(word);

  // tells the gui to updata                                                
  // gui::update(word,ave,isWord); // not finished yet                      

  return 0;
}

Вот test.cpp

#include <iostream>
#include <string>
#include <map>

#include "database.h" //this is my file                                              

using namespace std;

int main()
{
  // first test the constructor                                                      
  database * data;

  data->update("trail",3);
  data->update("mix",2);
  data->update("nut",7);
  data->update("and",8);
  data->update("trail",8);
  data->update("and",3);
  data->update("candy",8);

  //  cout<< (int) data->size()<<endl;                                               

  return 0;

}

Спасибо большое.Он компилируется и работает до cout << "test1" << endl;, но в следующей строке происходит ошибка.

Rusty

Ответы [ 2 ]

5 голосов
/ 12 апреля 2011

Вы никогда не создавали объект базы данных, просто указатель на никуда (возможно, вы привыкли к другому языку).

Попробуйте создать такой как database data;

А затем измените свой -> на ., чтобы получить доступ к членам.

Подумайте о приобретении одной из книг на The Definitive C ++ Book Guide и списке .

1 голос
/ 12 апреля 2011

Вам нужно выделить свою базу данных, прежде чем начинать вставлять в нее данные.

Изменение:

database *data;

до:

database *data = new database();

или

database data;

в main().

РЕДАКТИРОВАТЬ: если вы используете последний, измените -> на . при последующих вызовах методов. В противном случае, не забудьте delete ваш data объект после его использования.

...