String & String:: operator + (String &str1)//加号操作符的重载
{
if (this->pstr == NULL)
{
printf("String & String:: operator+ (String &str1) this==NULL err");
}
if (str1.pstr == NULL)
{
printf("String & String:: operator+ (String &str1) parameter err");
}
String p;//这个p虽然是局部变量但我也new了空间给他,我的编译器编译不通过,各位我这个题你们都写过吧,
//求解决方法和解释
p.len = this->len + str1.len + 1;
p.pstr = new char[p.len];
strcpy(p.pstr, pstr);
//puts(p.pstr);
strcat(p.pstr, str1.pstr);
puts(p.pstr);
free(this->pstr);
//this->pstr = p.pstr;
//strcat(p.pstr, str1.len+1, str1.pstr);
return p;
}

类的成员变量返回类的局部对象,这个对象中我已经new了空间,为什么不能返回呢?这个应该怎么做呢?
- 写回答
- 好问题 0 提建议
- 关注问题
- 邀请回答
-
2条回答 默认 最新
- Thu_zqh 2017-04-24 00:14关注
你没有new空间给它,如果用new的话是需要复制给一个String的指针,上述代码编译不过是因为你返回的是引用,而实际上是不能返回局部变量的引用,你把&去掉就可以返回局部变量的拷贝
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报