所以我的 CS 课作业给我带来了一些麻烦。目标是在不使用任何 cstring
函数的情况下创建我自己的非 NULL 终止的 String 类。类中的数据必须包含字符串的长度、称为“数据”的 char*
以及其他一些与我的问题无关的内容。
因此,当我为字符串分配内存时,我调用了 MyStrCopy(MyString* tar, const char* str)
函数,该函数使用 tar->data = new char[length ]
分配内存,“长度”是作为 str
传入的 cstring 的长度,它按预期工作。但是,当以这种方式分配内存时,数组总是比我指定的大得多(例如,我要求 6 个字节,但我得到的字节数超过了 11 个),而且我得到的字节数似乎是随机的,每次运行都不同。我尝试编写一个函数来剔除不需要的字符,但我认为我只是缺乏如何实现它的技能/知识。
这些额外的数据使我的一些功能变得不正常,我不知道如何修复它。有什么想法吗?
我在下面定义了我的类
#include <iostream>
#pragma once
class MyString {
private:
char* data;
int length;
static bool printAsUppercase;
int getLengnth(const char* str);
void MyStrCopy(MyString* tar, const char* str);
public:
// Constructors
MyString();
MyString(const char* data);
MyString(MyString& data2Copy);
~MyString();
// Operator Overloads
// Assignment Operator
MyString operator=(const MyString& data);
MyString operator=(const char* data);
// Arithmetic Operators
MyString operator+(const MyString& rightStr);
// Pre/Post decrement
MyString operator--();
MyString operator--(int);
// Boolean Operators
friend bool operator==(const MyString& leftStr, const MyString& rightStr);
friend bool operator>(const MyString& leftStr, const MyString& rightStr);
friend bool operator<(const MyString& leftStr, const MyString& rightStr);
// Streaming Operators
friend std::ostream& operator<<(std::ostream& os, const MyString& str);
friend std::istream& operator>>(std::ostream& is, MyString& str);
// Mutators
MyString& uppercase();
void cull();
// Accessors
int getLengnth();
};
这是实现。注意:其中大部分目前无法按预期工作。
#include "MyString.h"
// Constructors
MyString::MyString() {
data = NULL;
length = 0;
}
MyString::MyString(const char* data) {
MyStrCopy(this, data);
}
MyString::MyString(MyString& data2Copy) {
MyStrCopy(this, data2Copy.data);
}
MyString::~MyString() {
delete[] data;
}
MyString MyString::operator=(const MyString& data) {
MyString temp;
MyStrCopy(&temp, data.data);
return temp;
}
MyString MyString::operator=(const char* data) {
MyString temp;
MyStrCopy(&temp, data);
return temp;
}
void MyString::MyStrCopy(MyString* tar, const char* str) {
// WIP Something's not right with the NEW line
tar->length = getLengnth(str);
if (data != NULL)
delete data;
tar->data = new char[length];
for (int i = 0; i < tar->length; i++)
tar->data[i] = str[i];
tar->cull();
}
void MyString::cull() {
// WIP currently does effectively nothing
int currLen = getLengnth(data);
while (currLen > length)
data[currLen--];
}
int MyString::getLengnth() {
return length;
}
int MyString::getLengnth(const char* str) {
int len = 0;
while (str[len] != NULL)
len++;
return len;
}
提前致谢!
最佳答案
MyString::MyString(MyString& data2Copy) {
MyStrCopy(this, data2Copy.data);
}
这基本上默认构造了 MyString
的一个新实例,在调用 MyStrCopy()
之前没有初始化它的任何成员。在 MyStrCopy
中:
if (data != NULL)
delete data;
因为 data
和新类的任何其他成员都没有被初始化——出于上述原因,这里的 data
将是随机垃圾,来自这一点都是未定义的行为。
关于c++ - 使用 `new` 创建字符数组会生成比我指定的更多的字符。 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54282251/