コピーコンストラクタ

/****コピーコンストラクタを生成、オブジェクトを関数に渡す*****/
#include<iostream>
#include<cstring>
#include<cstdlib>
using namespace std;

class stringtype{
char *p;
public:
stringtype(char *s);
stringtype(const stringtype &ob);
~stringtype(){
delete []p;}
char *get(){
return p;
}
};
stringtype::stringtype(char *s)
{
int l;
l=strlen(s)+1;//strlen()method

p=new char[l];
if(!p){
cout<<"unable get a memory field"<<endl;
exit(1);
}
strcpy(p,s);//strcpy()method
}
stringtype::stringtype(const stringtype &ob)
{
int l;
l=strlen(ob.p)+1;

p=new char[l];
if(!p){
cout<<"unable get a memory field"<<endl;
exit(1);
}
strcpy(p,ob.p);//文字列をコピーオブジェクトにコピー
}

void show(stringtype x)
{
char *s;
s=x.get();
cout<<s<<endl;
}
int main()
{
stringtype e("see you"),d("good luck");

show(e),show(d);
return 0;
}

//出力結果

see you
good luck

No comments:

Post a Comment

Nikkei225

28000-28550 up in the early session, down lately.