我有这些变量:C++拷贝构造函数/赋值运算错误
char** wordList_;
int wordListCapacity_;
int* wordCountList_;
char* fileName_;
int nUniqueWords_;
int nTotalWords_;
int nTotalCharacters_;
我的拷贝构造函数:
FileIndex::FileIndex(const FileIndex& fi)
{
fileName_ = new char[strlen(fi.fileName_) + 1];
strcpy(fileName_, fi.fileName_);
cout << "Jiasd?" << endl;
wordListCapacity_ = fi.wordListCapacity_;
nUniqueWords_ = fi.nUniqueWords_;
nTotalWords_ = fi.nTotalWords_;
nTotalCharacters_ = fi.nTotalCharacters_;
wordList_ = new char*[wordListCapacity_];
wordCountList_ = new int[wordListCapacity_];
for(int i = 0; i < nUniqueWords_; i++) {
wordList_[i] = fi.wordList_[i];
wordCountList_[i] = fi.wordCountList_[i];
}
}
我的重载的赋值运算符:
FileIndex& FileIndex::operator=(const FileIndex& fi)
{
fileName_ = new char[strlen(fi.fileName_) + 1];
strcpy(fileName_, fi.fileName_);
wordListCapacity_ = fi.wordListCapacity_;
nUniqueWords_ = fi.nUniqueWords_;
nTotalWords_ = fi.nUniqueWords_;
nTotalCharacters_ = fi.nTotalCharacters_;
wordList_ = new char*[wordListCapacity_];
wordCountList_ = new int[wordListCapacity_];
for (int i = 0; i < nUniqueWords_; i++) {
wordList_[i] = new char[strlen(fi.wordList_[i])+1];
strcpy(wordList_[i], fi.wordList_[i]);
wordCountList_[i] = fi.wordCountList_[i];
}
return *this;
}
每当我创建一个FileIndex (称为FirstIndex
)并用意思初始化成员变量gful(NOT NULL)我有这些线测试拷贝构造函数和赋值操作符:
FileIndex secondIndex = firstIndex;
FileIndex thirdIndex;
secondIndex = thirdIndex; // Segmentation fault here
我与赋值运算符分段错误,但我有一种感觉,可能是因为拷贝构造函数故障代码。也就是说,如果复制构造函数中有错误,那么在赋值运算符中也可能有一个错误。
在此先感谢您的帮助!
简化课程会发生什么? – Beta 2012-02-09 00:17:43
你的析构函数是什么样的? – 2012-02-09 00:17:45
改为使用'std :: vector',你的问题可能会消失。还要了解* ctor-initializer *列表。 – 2012-02-09 00:18:39