【发布时间】:2017-11-02 16:56:06
【问题描述】:
所以我创建了一个名为 WordFrequency 的类,它将一个字符串单词和一个 int 频率存储为私有成员变量。 一个 HashTable 函数,其中包含一个 WordFrequency** 、 hashsize 、 hashtable 中的 currentitems。
在使用复制构造函数时,我总是遇到错误 - 线程 1:EXC_BAD_ACCESS(代码=1,地址=0x0) 当在复制构造函数中调用时,它会将我重定向到 WordFrequency 类的 getter 函数。 我无法弄清楚为什么会这样。
复制构造函数。
Hashtable:: Hashtable(const Hashtable &hash){
WordFrequency** temp = new WordFrequency* [hash.hashSize];
this->arr = temp;
for (int i = 0 ; i < hash.hashSize ; i++) {
if (hash.arr[i] == NULL){ //pointer in hashstable is null
continue;
}
//bucket is not empty
if(this->search(this->arr[i]->getWord()) != 0 ){ //if same string already found in this hashtable
this->arr[i]->increment(); // incrtement the frequency
continue;
}
//else the string doest even exist in the hashtable.
WordFrequency x ((hash.arr[i])->getWord()); //deep copying the word from the parameter hash
temp[i] = &x; //pointing the hash table to the new the object
}
this->hashSize = hash.hashSize;
this->currentItems = hash.currentItems;
}
词频类中的getter函数。
string WordFrequency:: getWord() const {
return this->word;
}
虽然getter函数看起来很简单,但不知道为什么会出现这个错误。
我还包括我的析构函数,这可能是问题所在。
Hashtable:: ~Hashtable() {
for (int i = 0 ; i < this->hashSize ; i++){
delete this->arr[i];
}
delete [] this->arr;
this->hashSize = 0;
this->currentItems = 0;
}
输出运算符 -
ostream& operator<< (ostream &out, const Hashtable &h){
out << "Hashtable with size - " << h.hashSize << "and no of elements - " << h.currentItems << endl;
for (int i = 0 ; i < h.hashSize ; i++){
if (h.arr[i] == NULL){
out << "0";
continue;
}
else {
out << ((h.arr[i])->getWord()); //bad access
}
}
out << endl;
return out;
}
【问题讨论】:
-
使用 std::vector
! -
" 我总是收到一个错误 - 线程 1: EXC_BAD_ACCESS" 好的,我相信您的环境会让您运行调试器并查看确切的堆栈跟踪使用函数参数值导致该错误,以便您可以了解访问错误的原因。
-
我认为分配需要使用自定义哈希表?如果没有,您可以使用
std::map或std::unordered_map为自己省去很多麻烦。
标签: c++ class oop exc-bad-access copy-constructor