我正在尝试做一个家庭作业,我们使用链接堆栈将字符串插入到字符串中的指定点,因此是 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 类具有空的构造函数和析构函数。
最佳答案
只是一个提示:C++ 中的运行时错误与公共(public)/ protected /私有(private)访问完全无关。编译器在编译您的代码时,已经检查是否遵循了所有类成员访问规则。
运行时错误意味着您的程序中存在错误,很可能是某种内存损坏。
关于 protected 成员的 C++ 运行时错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1547342/