code.club

 找回密碼
 立即註冊
搜索
查看: 5687|回復: 0
打印 上一主題 下一主題

c++問題請教

[複製鏈接]
跳轉到指定樓層
樓主
發表於 2015-8-27 19:48:01 | 只看該作者 回帖獎勵 |倒序瀏覽 |閱讀模式
下面這程式,請問紅字的部份?謝謝。

#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;
}
__________________
回復

使用道具 舉報

您需要登錄後才可以回帖 登錄 | 立即註冊

本版積分規則

小黑屋|手機版|Archiver|code.club  

GMT+8, 2024-4-25 15:21 , Processed in 0.090946 second(s), 17 queries .

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回復 返回頂部 返回列表