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中使用 malloc 和 free 来分配、释放内存
在C++中是使用 new 和 delete ,格式:
类型名 * 指针 = new 类型名;
delete 指针;
e.g. char * str = new char;
则 delete str;
e.g. 对数组使用:
char * str = new char[10]; //[]中填分配长度(数组长度)
则 delete [] str; // 注意不要漏掉[]