主題: C++ 請教
查看單個文章
  #1  
舊 2015-08-27, 06:39 PM
哈啦 的頭像
哈啦 哈啦 目前離線
論壇管理員
 
註冊日期: 2002-05-28
文章: 22,997
預設 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
回覆時引用此篇文章