C++习题EasyString


Question:


This time, you need to create two function:

void Assign(char * & str, int & length); According to the length, allocate memory to str.
void AddTwo(string & res, char * & str1, char * & str2); Add str1 and str2, then assign the result to the res. More importantly, you need to handle str1 and str2 to guarantee that there would not happen memory problem.


Sample input:

4 5
abcd
efghi


Sample ouput:

abcd
efghi
abcdefghi


StringMain.cpp

#include <iostream>
#include "EasyString.hpp"

using namespace std;
int main() {
  int length;
  char* str0 = NULL, * str1= NULL;
  cin >> length;
  Assign(str0, length);
  cin >> length;
  Assign(str1, length);
  cin >> str0 >> str1;
  cout << str0 << endl << str1 << endl;
  string res = "";
  AddTwo(res, str0, str1);
  cout << res << endl;
}

EasyString.hpp

#ifndef EasyStr
#define EasyStr
#include <iostream>
using std::cin;
using std::string;
void Assign(char * &, int &);//此处的&是什么意义?
void AddTwo(string &, char * &, char * &);
#endif
/*reference引用运算符,可以改变实际传递过来的参数(谓实参),C标准不可用*/
/*定义一个string类型变量的引用,相当于给现有变量起个别名,与指针还是不一样的。比如string a;string& b=a;这两句,b与a实际上是一回事,表示的是同一块内存。*/
/*此处由于返回值类型为void,用&引用前面定义的res,str0,str1;若去掉&,则执行该函数之后res,str0,str1的值不会改变*/

EasyString.cpp*

#include "EasyString.hpp"
void Assign(char * &str, int &length){
  str = new char[length+1];
}
void AddTwo(string &res, char * &str0, char * &str1){
  res += str0;
  res += str1;
  delete [] str0;      //关于char* 的new和delete
  delete [] str1;
}
如何将char * 拷贝到 string
char* s="good boy";
string str=s;

或者

char s[20]="good boy";
string str=s;

关于new 和 delete
在C中使用 mallocfree 来分配、释放内存
在C++中是使用 newdelete ,格式:
    类型名 * 指针 = new 类型名;
    delete 指针;
    e.g. char * str = new char;
              则  delete str;
    e.g. 对数组使用:
        char * str = new char[10]; //[]中填分配长度(数组长度)delete [] str;  // 注意不要漏掉[]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值