C++ 請教
下面這程式,請問紅字的部份?謝謝。
#include <iostream>
using namespace std;
class strtype {
char *p;
int len;
public:
strtype(char* ptr);
~strtype();
void show();
};
strtype::strtype(char *ptr){
len=strlen(ptr);
p=(char*)malloc(sizeof(len+1));//為何這裡要加一?不用加一也可以啊?
if(!p) {
cout<<"Allocation error.\n";
exit(1);
}
strcpy(p,ptr);
}
strtype::~strtype(){
free(p);
}
void strtype::show(){
cout<< "The length of "<< p <<" is "<<len<<endl;
}
int main(){
strtype s1("Hello world!"),s2("This is a book.");
s1.show();
s2.show();
return 0;
}
|