我目前正在学习C++课程的第二序列。我正在使用c-strings &动态内存建立自己的字符串类。
我的大部分代码都可以使用。我正在读取一个文件,并将每个单词放入我的类类型 "ATString "的向量中。我们应该把读进来的5个词组合成一个巨型词,然后把它放到另一个向量中。当我用调试器一步步查看我的代码时,我看到单词组合,它正在将单词复制到新的ATString变量 "tempJumbo "中。运行了几行后,程序崩溃,并告诉我我的程序已经触发了一个断点,让我在第96行的加法运算符函数。
这里是operator+的定义。
ATString ATString::operator+ (ATString& string1) {
int newSize = length() + string1.length();
ATString newString;
if (newSize > 20) { // increase capacity if size is greater than 20 characters
newString.increase_cap();
}
else {
cap = 20;
}
newString.strPtr = new char[newString.cap];
newString.end = newSize;
for (int i = 0; i < length(); i++) {
newString[i] = strPtr[i];
for (int j = length(); j < newSize; j++) {
newString[j] = string1.strPtr[j-end];
}
return newString;
}
这里是main, 读取文件并试图将这些词组合成一个巨型词.
int main() {
vector<ATString> words(100);
vector<ATString> lines(100); // calls default constructor 100 times
ifstream fin("infile3.txt");
int index = 0;
int wordCount = 0;
//READ
if (fin.fail()) {
cout << "Couldn't open infile2.txt" << endl;
system("pause");
exit(1);
}
while (!fin.eof()) {
fin >> words[index];
index++;
}
wordCount = index;
words.resize(wordCount);
//COMBINE 5 WORDS INTO ONE JUMBO
ATString tempJumbo;
int j = 0;
for (int i = 0;i < wordCount; i++) {
tempJumbo = words[i] + words[i+1] + words[i+2] + words[i+3] + words[i+4];
lines[j] = tempJumbo; // putting big word into lines vector
tempJumbo = " "; //resetting variable to hold jumbo word?
i = i + 4;
j++;
if (i == wordCount) {
break;
}
}
return 0;
}
我写的destructor也有问题......它很简单,当我激活这个时,它也会触发一个错误并使程序崩溃。我不知道这是怎么回事。
ATString::~ATString() {
delete strPtr;
}
下面是我的头文件。
#ifndef ATSTRING_H
#define ATSTRING_H
#include <istream>
using namespace std;
class ATString {
public:
ATString();// default constructor
ATString(const char* cstr); // cstring constructor
ATString(const ATString& argstr); // copy constructor
~ATString(); // destructor
ATString& operator = (const ATString& objToCopy); // assignment operator =
ATString operator + (ATString& string1); // addition operator +
int length() const;
int capacity() const;
void increase_cap();
char& operator [] (int index); // indexing operator
const char& operator [] (int index) const; // const indexing operator
bool operator <(const ATString& argstr) ;
bool operator > (const ATString& argstr) ;
bool operator ==(const ATString& argstr);
friend istream& operator >> (istream& inStrm, ATString& argstr); // extraction operator
friend const ostream& operator << (ostream& outStrm, const ATString& argstr); // insertion opertator
private:
char* strPtr;
int end;
int cap;
int compareTo(const ATString& argStr);
};
#endif
谢谢你!
你的输入文件有多大?如果它是100个字或更多,那么你的索引在行上跑出了边界,当i=96,即试图获取word[100]元素。
tempJumbo = words[i] + words[i+1] + words[i+2] + words[i+3] + words[i+4] 。