![]() |
#2
hoho5682011-10-02 14:15
|

#include<iostream>
using namespace std;
class CStrtemp
{
public:
CStrtemp(char *s);
CStrtemp(const CStrtemp&);
~CStrtemp();
void show();
void set(char *s);
private:
char *str;
};
CStrtemp::CStrtemp(char *s)
{
cout<<"constructor."<<endl;
str=new char[strlen(s)+1];
if(!str)
{
cout<<"Allocation Error."<<endl;
exit(1);
}
strcpy(str,s);
}
CStrtemp::CStrtemp(const CStrtemp& temp)
{
cout<<"copy constructor."<<endl;
str=new char[strlen(temp.str)+1];
if(!str)
{
cout<<"Allocation Error."<<endl;
exit(1);
}
strcpy(str,temp.str);
}
CStrtemp::~CStrtemp()
{
cout<<"destructor."<<endl;
if(str!=NULL)
{
delete[] str;
}
}
void CStrtemp::show()
{
cout<<str<<endl;
}
void CStrtemp::set(char *s)
{
delete[] str;
str=new char[strlen(s)+1];
if(!str)
{
cout<<"Allocation Error."<<endl;
exit(1);
}
strcpy(str,s);
}
CStrtemp Input(CStrtemp temp)
{
char s[20];
cout<<"Please input the string:";
cin>>s;
temp.set(s);
return temp;
}
int main()
{
CStrtemp A("hello");
A.show();
CStrtemp B=Input(A);//此处对象B的创建不需要调用复制构造函数吗,形式上为对象复制的一般格式<类名><对象2>=<对象1>;,为什么没调用?
A.show();
B.show();
return 0;
}
using namespace std;
class CStrtemp
{
public:
CStrtemp(char *s);
CStrtemp(const CStrtemp&);
~CStrtemp();
void show();
void set(char *s);
private:
char *str;
};
CStrtemp::CStrtemp(char *s)
{
cout<<"constructor."<<endl;
str=new char[strlen(s)+1];
if(!str)
{
cout<<"Allocation Error."<<endl;
exit(1);
}
strcpy(str,s);
}
CStrtemp::CStrtemp(const CStrtemp& temp)
{
cout<<"copy constructor."<<endl;
str=new char[strlen(temp.str)+1];
if(!str)
{
cout<<"Allocation Error."<<endl;
exit(1);
}
strcpy(str,temp.str);
}
CStrtemp::~CStrtemp()
{
cout<<"destructor."<<endl;
if(str!=NULL)
{
delete[] str;
}
}
void CStrtemp::show()
{
cout<<str<<endl;
}
void CStrtemp::set(char *s)
{
delete[] str;
str=new char[strlen(s)+1];
if(!str)
{
cout<<"Allocation Error."<<endl;
exit(1);
}
strcpy(str,s);
}
CStrtemp Input(CStrtemp temp)
{
char s[20];
cout<<"Please input the string:";
cin>>s;
temp.set(s);
return temp;
}
int main()
{
CStrtemp A("hello");
A.show();
CStrtemp B=Input(A);//此处对象B的创建不需要调用复制构造函数吗,形式上为对象复制的一般格式<类名><对象2>=<对象1>;,为什么没调用?
A.show();
B.show();
return 0;
}
只有本站会员才能查看附件,请 登录