我在动态分配方面遇到了麻烦。在我的代码中 我正确初始化动态数组吗? 当我尝试为我的类String编写+运算符成员时,它不会返回我想要的内容。对正确路径的任何指导都会很棒。
实施例
String s1("One");
String s2("Two");
String s3 = s1+ s1;
cout <<s3;
//Output is OneTwo
cout <<s1;
//OUtput is OneTwo.
另外,我不明白为什么我不能将delete [] buf添加到我的构造函数中。
class String{
public:
String (const char *s =""):buf(new char[strlen(s)]){
buf = strdup(s);
};
String (const String &s):buf(new char[strlen(s.buf)]){
buf = strdup(s.buf);
delete []buf;
};
String operator =(const String &s){
return buf =strdup(s.buf);
};
char & operator [] (int index){
assert(inBounds(index));
return buf[index];
};
int size()
{
return strlen(buf);
};
String operator + (const String s){
delete []buf;
char *temp = new char[strlen(buf)+strlen(s.buf)];
///NEed to ask about t*his acan get this operator tor work
cout<< s.buf;
return temp;
};
String operator += (const String s){
strcpy(buf + strlen(buf),s.buf);
return buf;
};
void print(ostream & out){
out << buf;
};
void read (istream & in){
in >> buf;
};
~String(){
//delete [] buf;
};
private:
bool inBounds(int x){
return x >= 0 && x < strlen(buf);
};
static int strlen(const char *s){
int len =0;
for(int i=0;s[i] != '\0';i++)
len++;
return len;
};
static char *strcpy(char *dest,const char *src){
int i=0;
for(;(dest[i] = src[i]); ++i);
dest[i] = '\0';
return dest;
};
static char *strdup(const char *s){
char * buf;
buf = new char[strlen(s)+1];
int i=0;
for(;s[i] != '\0';i++)
buf[i] = s[i];
buf[i] = '\0';
return buf;
}
char * buf;
};
答案 0 :(得分:1)
你的第一个构造函数
String (const char *s ="") : buf(new char[strlen(s)]){
buf = strdup(s);
}
首先分配一个字符太小的缓冲区,然后通过将buf
指向strdup
的结果将其抛出 - 内存泄漏。
你想要
String (const char *s ="") : buf(new char[strlen(s) + 1]){
strcpy(buf, s);
}
或
String (const char *s ="") : buf(strdup(s))
{
}
你的第二个构造函数
String (const String &s) : buf(new char[strlen(s.buf)]){
buf = strdup(s.buf);
delete []buf;
};
内存泄漏存在同样的问题,并且会立即解除分配buf
的复杂性。
你想要像
这样的东西String (const String& s) : buf(strdup(s.buf))
{
}
您的+
解除分配buf
,分配未初始化(和太小)的缓冲区,打印buf
(未定义),然后返回未初始化的String
缓冲。
加法运算符不应修改*this
;它应该使用+=
,看起来像
String operator+ (const String& s) const
{
String result = *this;
result += s;
return result;
};
哪个离开+=
,需要将buf
重新分配为足以保存结果。
我会把它留作练习。
使用标准名称重新实现标准库函数非常容易混淆。