0

我正在我自己的班级中使用多图进行项目,并且遇到了段错误。这是我的代码中与该问题相关的部分。我真的很感激一些帮助。谢谢。

这是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:

};

这是database.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;但在下一行出现段错误。

生锈的

4

2 回答 2

5

您实际上从未创建过数据库对象,只是一个指向无处的指针(也许您已经习惯了另一种语言)。

尝试创建一个这样的database data;

然后将您->的更改.为访问成员。

考虑在The Definitive C++ Book Guide and List中获取其中一本书。

于 2011-04-12T17:17:24.010 回答
1

在开始插入数据之前,您需要分配数据库。

改变:

database *data;

到:

database *data = new database();

或者:

database data;

main().

EDIT: if you use the latter, change -> to . on the subsequent method calls. Otherwise, remember to delete your data object after using it.

于 2011-04-12T17:21:04.397 回答