gpt4 book ai didi

c++ - C++ 的基本自定义字符串类

转载 作者:行者123 更新时间:2023-11-30 01:00:30 24 4
gpt4 key购买 nike

编辑:我不想删除帖子,因为我很快从中学到了很多东西,它可能对其他人有好处,但其他任何人都不需要花时间回答或查看这个问题。问题出在我的编程基础上,这是无法通过快速响应解决的问题。对于所有发布者,感谢您的帮助,非常谦虚!

大家好,我正在构建我自己的具有非常基本功能的字符串类。我很难理解我定义的基本类发生了什么,并且相信在处理发生的范围时存在某种错误。当我尝试查看我创建的对象时,所有字段都被描述为(显然是错误的指针)。此外,如果我公开数据字段或构建访问器方法,程序就会崩溃。由于某种原因,该对象的指针是 0xccccccccc,它没有指向任何地方。
我该如何解决这个问题?非常感谢任何帮助/评论。

    //This is a custom string class, so far the only functions are 
//constructing and appending

#include<iostream>
using namespace std;

class MyString1
{
public:
MyString1()
{

//no arg constructor
char *string;
string = new char[0];
string[0] ='\0';
std::cout << string;
size = 1;
}
//constructor receives pointer to character array
MyString1(char* chars)
{
int index = 0;
//Determine the length of the array
while (chars[index] != NULL)
index++;
//Allocate dynamic memory on the heap
char *string;
string = new char[index+1];
//Copy the contents of the array pointed by chars into string, the char array of the object
for (int ii = 0; ii < index; ii++)
string[ii] = chars[ii];
string[index+1] = '\0';
size = index+1;
}
MyString1 append(MyString1 s)
{
//determine new size of the appended array and allocate memory
int newsize = s.size + size;
MyString1 MyString2;
char *newstring;
newstring = new char[newsize+1];

int index = 0;
//load the first string into the array
for (int ii = 0; ii < size; ii++)
{
newstring[ii] = string[ii];
index++;
}

for(int jj = 0; jj < s.size; jj++, ii++)
{
newstring[ii] = s.string[jj++];
index++;
}
//null terminate
newstring[newsize+1] = '\0';

delete string;
//generate the object for return
MyString2.string=newstring;
MyString2.size=newsize;

return MyString2;
}
private:
char *string;
int size;
};



int main()
{
MyString1 string1;
MyString1 string2("Hello There");
MyString1 string3("Buddy");
string2.append(string3);
return 0;
}

编辑:感谢到目前为止所有回应并处理我对这个主题的大量缺乏理解的人。我将开始处理所有的答案,但再次感谢您的好评,抱歉我的问题含糊不清,但实际上并没有具体的错误,更多的是缺乏对数组和类的理解。

最佳答案

这里只是第一个构造函数的错误。

    MyString1()     
{

//no arg constructor
char *string; //defines local variable that hides the member by that name
string = new char[0]; //sort of meaningless
string[0] ='\0'; //not enough room for that (out-of-bounds)
std::cout << string;
size = 1; //I don't think you should count null as part of the string
}

其他地方也有类似的错误。

此外,您还应该以更谨慎的方式传递参数。

MyString1(const char* source); //note const

MyString1 append(const MyString1& what); //note const and reference

如果后者是正确的,还取决于它应该做什么。基于 std::string,预期结果为:

MyString1 a("Hello "), b("world");
a.append(b);
assert(a == "Hello world");

关于c++ - C++ 的基本自定义字符串类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2609229/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com