我正在尝试做一个家庭作业,我们使用链接堆栈将字符串插入到指定点的字符串中,因此是struct和typedef。无论如何,当我尝试在 InsertAfter 方法内的 StringModifier 类中访问 stringLength 时,我得到一个运行时错误,我无法弄清楚问题是什么。我应该能够访问和修改变量,因为它受到保护并且派生类是公开继承的。
struct StringRec
{
char theCh;
StringRec* nextCh;
};
typedef StringRec* StringPointer;
class String
{
public:
String();
~String();
void SetString();
void OutputString();
int GetLength() const;
protected:
StringPointer head;
int stringLength;
};
class StringModifier : public String
{
public:
StringModifier();
~StringModifier();
void InsertAfter( StringModifier& subString, int insertAt );
};
void StringModifier::InsertAfter( StringModifier& subString, int insertAt )
{
// RUN TIME ERROR HERE
stringLength += subString.stringLength;
}
在主要
StringModifier test;
StringModifier test2;
cout << "First string" << endl;
test.SetString();
test.OutputString();
cout << endl << test.GetLength();
cout << endl << "Second string" << endl;
test2.SetString();
test2.OutputString();
cout << endl << test2.GetLength();
cout << endl << "Add Second to First" << endl;
test.InsertAfter( test2, 2 );
test.OutputString();
cout << endl << test.GetLength();
//String Class
String::String()
{
head = NULL;
stringLength = 0;
}
String::~String()
{
// Add this later
}
void String::SetString()
{
StringPointer p;
char tempCh;
int i = 0;
cout << "Enter a string: ";
cin.get( tempCh );
// Gets input and sets it to a stack
while( tempCh != '\n' )
{
i++;
p = new StringRec;
p->theCh = tempCh;
p->nextCh = head;
head = p;
cin.get( tempCh );
}
stringLength = i;
}
void String::OutputString()
{
int i = stringLength;
int chCounter;
StringPointer temp;
// Outputs the string bottom to top, instead of top to bottom so it makes sense when read
while( head != NULL && i > 0 )
{
temp = head;
chCounter = 0;
while( temp != NULL && chCounter < (i-1) )
{
temp = temp->nextCh;
chCounter++;
}
cout << temp->theCh;
i--;
}
}
int String::GetLength() const
{
return stringLength;
}
StringModifier 类有空的构造函数和析构函数。