class MyString
{
public:
MyString();
MyString(int newsize);
MyString(const MyString& ms);
const MyString& operator=(const MyString& ms);
virtual ~MyString();
private:
int *ptr;
int size;
};
/////
MyString::MyString(int newsize)
{
size = newsize;
ptr = new int[size];
for(int i=0; i < size; i++){
ptr[i] = 0;
}
cout<<"construct is executing size is "<<size<<endl;
}
MyString::MyString(const MyString& ms){
size = ms.size;
ptr = new int[size];
for(int i = 0; i < size ; i++){
ptr[i] = ms.ptr[i];
}
cout<<"copy construct is executing.."<<"address of ptr is "<<ptr<<endl;
}
const MyString& MyString::operator=(const MyString& ms){
cout<<"operator is executing"<<endl;
if(this != &ms){
delete[] ptr;
size = ms.size;
ptr = new int[size];
for(int i = 0; i < size ; i++){
ptr[i] = ms.ptr[i];
}
return *this;
}
}
MyString::~MyString()
{
cout<<"desturct address of ptr is "<<ptr<<endl;
delete[] ptr;
}
////////////
MyString play(MyString a)
{
return a;
}
int main(int argc, char* argv[])
{
//printf("Hello World!\n");
/*testint t1 = play(4);
testint t2 = play(5);
testint t3 = play(t1);*/
MyString ms1 = MyString(5);
MyString ms2 = play(ms1);
return 0;
}
////
输出结果:
注意将play(ms1)的返回值赋值给ms2,执行拷贝函数。然后返回值再析构
{
public:
MyString();
MyString(int newsize);
MyString(const MyString& ms);
const MyString& operator=(const MyString& ms);
virtual ~MyString();
private:
int *ptr;
int size;
};
/////
MyString::MyString(int newsize)
{
size = newsize;
ptr = new int[size];
for(int i=0; i < size; i++){
ptr[i] = 0;
}
cout<<"construct is executing size is "<<size<<endl;
}
MyString::MyString(const MyString& ms){
size = ms.size;
ptr = new int[size];
for(int i = 0; i < size ; i++){
ptr[i] = ms.ptr[i];
}
cout<<"copy construct is executing.."<<"address of ptr is "<<ptr<<endl;
}
const MyString& MyString::operator=(const MyString& ms){
cout<<"operator is executing"<<endl;
if(this != &ms){
delete[] ptr;
size = ms.size;
ptr = new int[size];
for(int i = 0; i < size ; i++){
ptr[i] = ms.ptr[i];
}
return *this;
}
}
MyString::~MyString()
{
cout<<"desturct address of ptr is "<<ptr<<endl;
delete[] ptr;
}
////////////
MyString play(MyString a)
{
return a;
}
int main(int argc, char* argv[])
{
//printf("Hello World!\n");
/*testint t1 = play(4);
testint t2 = play(5);
testint t3 = play(t1);*/
MyString ms1 = MyString(5);
MyString ms2 = play(ms1);
return 0;
}
////
输出结果:
注意将play(ms1)的返回值赋值给ms2,执行拷贝函数。然后返回值再析构