gpt4 book ai didi

c++ - C 风格的字符串和 C++ 中的运算符重载

转载 作者:行者123 更新时间:2023-11-27 22:56:06 25 4
gpt4 key购买 nike

<分区>

我试图在我自己的 C 风格 版本的 string 类上重载 + 运算符。

除了显示垃圾值的第二个字符串 s2display() 调用外,一切都很好。

class string_ {

char *str;
int len;

public :
...
void display()
{
cout << str;
}
};

string_ :: string_()
{
str = 0;
len = 0;
}

string_ :: ~string_()
{
delete []str;
len = 0;
}


string_ :: string_(char *s,int l)
{
len = l + 1; // +1 for \0
str = new char[len];
int i;
for(i=0;i<len;i++)
str[i] = s[i];
str[i] = '\0';
}

string_ string_ :: operator +(string_ c)
{
int j = 0, i = 0;
string_ s;
s.len = len + c.len - 1;
s.str = new char[s.len];
while (str[i] != '\0')
{s.str[i] = str[i]; i++;}

while (c.str[j] != '\0')
{s.str[i] = c.str[j]; i++; j++; }

s.str[i] = '\0';
//The below statements gives the desired output
cout <<"\nIN operator +" << str;
cout <<"\nIN operator +" << c.str;
cout <<"\nIN operator +" << s.str;
return s;
}

int main()
{
char *str = "Hello";
char *str1 = " World";
string_ s1(str,5);
string_ s2(str1,6);
string_ s3 = s1 + s2;
cout << "\nstring s1 : ";
s1.display();
cout << "\nstring s2 : ";
s2.display(); //PROBLEM
cout << "\nConcatenated string : ";
s3.display();
return 0;
}

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