【发布时间】:2011-02-06 05:51:16
【问题描述】:
编辑:我不想删除帖子,因为我很快从中学到了很多东西,它可能对其他人有好处,但其他人没有必要花时间回答或查看这个问题。问题出在我的编程基础上,而这是无法通过快速响应解决的。感谢所有发帖的人,感谢您的帮助,非常谦虚!
大家好,我正在构建自己的具有非常基本功能的字符串类。我很难理解我定义的基本类发生了什么,并且相信在处理发生的范围时存在某种错误。当我尝试查看我创建的对象时,所有字段都被描述为(显然是错误的指针)。此外,如果我公开数据字段或构建访问器方法,程序会崩溃。由于某种原因,该对象的指针是 0xccccccccc,它不指向任何位置。
我该如何解决这个问题?非常感谢任何帮助/cmets。
//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;
}
编辑: 感谢到目前为止所有回复并处理我对这个主题的严重缺乏理解的人。我将开始处理所有答案,但再次感谢您的良好回复,抱歉我的问题含糊不清,但实际上并没有具体的错误,但更多的是缺乏对数组和类的理解。
【问题讨论】:
-
为什么不使用
std::basic_string? -
由于我还在学习 C++,因此我正在尝试将课程构建为练习。
-
仅供参考,
0xcccccccc地址是 Microsoft 编译器在调试模式下编译时填充未初始化内存的特殊值。当您看到该值时,您可以合理确定地知道您要么忘记初始化变量,要么取消引用已删除或其他野指针。 -
要添加到 Tyler 的评论中,请参阅 stackoverflow.com/questions/370195/…