字符串类 = 运算符
String class = operator
我正在努力构建自己的字符串类,但在使用子字符串时遇到了一些问题
// Substring operator
// reutns a substring from a given point
String String::Substring(int startPosition, int length) const{
if(length==0)
length = GetLength()+1; //Takes care of null terminator, im not worried about if length is imputed yet
char* result = new char[length-startPosition]; // Assume it's not negative for the sake of just getting it to work, It would only be negative if it's user error
for(int i=startPosition; i<length; i++)
result[i] = Text[i]; //Since it will always go from a given point to the end, the null terminator will transfer in the for loop.
return result;
}
文本是字符串类的数据成员。我收到一个未处理的异常,访问冲突读取位置。
当我调试它正在经历这些过程时
// Init-constructor for initializing this string with a C-string
String::String(const char* text){
*this = text;
}
和
// Assigns C-string to this String
String& String::operator = (const char* text){
// Delete the existing string first
delete[] Text;
// +1 accounts for null terminator
int trueLength = GetLength(text)+1;
// Allocate new memory
Text = new char[trueLength];
// Copy all characters from source into Text
for ( int i = 0; i < trueLength; i++)
Text[i] = text[i];
return *this;
}
我不知道我做错了什么,谢谢你的帮助。
考虑使用 char*
构造函数创建 String 对象时会发生什么情况:
String::String(const char* text){
*this = text;
}
尚未初始化任何成员,并且您调用operator=
:
String& String::operator = (const char* text){
// Delete the existing string first
delete[] Text;
删除成员Text
,即使尚未初始化它。删除单位化指针会产生未定义的行为。在这种情况下,行为是一个例外。
在调用 operator=
之前,要么在构造函数中将Text
初始化为 null,要么在构造函数中执行所有工作,而不是赋值运算符。
当你分配length-startPosition
时,你很可能使用负数。
只用长度做新的:
char* result = new char[length];
编辑:
从i=0
开始复制,并将最后一个复制字符后面的字节设置为 null:
for(int i=0; i<length; i++)
result[i] = Text[i+startPosition];
result[i] = ' ';
相关文章:
- 我可以使用条件运算符初始化C风格的字符串文字吗
- 为什么字符串比较的 == 运算符相对于任一字符串长度线性时间(似乎)?
- 是否可以将带有字符串化运算符的宏转换为 constexpr?
- 在 c++ 中对字符串进行操作的关系运算符无法按预期工作
- Qt PL/SQL - 赋值运算符 - 字符串缓冲区太小
- 重载 std::字符串运算符+ 用于打印枚举名称
- <<运算符优先级与字符串比较
- C++ |<<运算符重载和打印字符串
- ">"运算符和"<"运算符如何进行字符串比较?
- 字符串数组上的 sizeof 运算符以 C++ 为单位给出不同的输出
- 重载加法运算符(使用函数向对象添加字符串)
- 使用短运算符的字符串连接有区别吗?
- 为什么在C++中使用关系运算符创建的模板函数不能对字符串正常工作?
- 使用 cout 运算符重载字符串
- 如何使用运算符>>在自定义字符串中输入多个单词?
- C++中的字符串类: +运算符中的错误?
- 在 c++ 中对字符串进行加号运算符
- 为什么sub_match和basic_string比较运算符使用额外的字符串副本实现?
- R 值重载运算符字符串赋值错误
- (c++)更长的算术运算符字符串