code.club

標題: c++問題請教 [打印本頁]

作者: enter    時間: 2015-8-27 19:48
標題: 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;
}
__________________




歡迎光臨 code.club (http://code.club/) Powered by Discuz! X3.2