所以我为我的CS课程分配了一些给我带来麻烦的作业.目标是在不使用任何cstring函数的情况下创建我自己的非NULL终止的String类.类中的数据必须包含字符串的长度,名为“data”的char *,以及
所以当我为字符串分配内存时,我调用MyStrCopy(MyString * tar,const char * str)函数,该函数使用tar-> data = new char [length]来分配内存,“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;
由于数据或新类的任何其他成员都没有被初始化 – 由于上述原因,这里的数据将是随机垃圾,从这一点开始,它就是所有未定义的行为.
