【发布时间】:2013-01-04 12:04:32
【问题描述】:
我制作了自己的类字符串 它有两个属性 buff 来存储字符串和长度 当我编译我的代码时 它工作正常,但如果我使用它 String 作为对象,我会得到很多错误 错误的原因是什么以及如何防止它们 谢谢
#include <iostream>
using namespace std;
class String
{
private:
int length;
char *buff;
public:
String operator=(String &);
String();
String(String &);
String(char *);
int size(char *);
void copy(char *);
char getvalue(int);
char *getbuff(){return buff;}
void setindex(char,int);
int getlength();
void display();
~String();
};
String :: String()
{
length = 1;
buff = 0;
}
String :: String(String &temp)
{
length = size(temp.buff);
buff = new char[temp.length + 1];
copy(temp.buff);
}
String :: String(char *a)
{
length = size(a);
buff = new char [length + 1];
copy(a);
}
int String :: size(char *a)
{
int i;
for(i = 0;a[i] != '\0';i++)
{
}
return i;
}
void String :: copy(char *a)
{
delete []buff;
int i;
length = size(a);
buff = new char[length + 1];
for (i=0;i<length;i++)
{
buff[i] = a[i];
}
buff[i] = '\0';
}
char String :: getvalue(int index)
{
return buff[index];
}
void String :: setindex(char value,int index)
{
buff[index] = value;
}
int String :: getlength()
{
return length;
}
void String :: display()
{
for (int i = 0;i<length;i++)
cout << buff[i];
}
String :: ~String()
{
delete []buff;
}
String String :: operator=(String &temp)
{
copy(temp.buff);
return *this;
}
void main()
{
String a("r");
String b("ee");
b = a;
b.display();
}
【问题讨论】:
-
您遇到了什么错误?我认为这只是一个练习,因为 C++ 已经有一个字符串类。学习使用 const。并且主要返回 int 不是 void
-
你需要遵守三法则。
-
我将其保存为我发布的答案..
-
阅读The Rule of Three,然后阅读this question。如果您仍然不清楚,请阅读一本书。
-
@CashCow 我得到的错误是块类型是有效的
标签: c++ string heap-memory