开辟内存空间的疑问
程序1:#include <iostream.h>#include <string.h>
class CSample
{
char *p1, *p2;
public:
void init(char *s1, char *s2);
void print()
{
cout<<"p1 ="<<p1<<'\n'<<"p2 = "<<p2<<'\n';
}
void copy(CSample &one);
void free();
};
void CSample::init(char *s1, char *s2)
{
p1=new char[strlen(s1)+1];
p2=new char[strlen(s2)+1];
strcpy(p1,s1);
strcpy(p2,s2);
}
void CSample::copy(CSample &one)
{
if (this!=&one ) *this=one;
}
void CSample::free()
{
delete[] this->p1;
delete[] this->p2;
}
void main()
{
CSample a,b;
a.init("My name is ","andrew");
a.print();
b.copy(a);
b.print();
a.free();
}
程序2:
#include <iostream.h>
#include <string.h>
class CStrOne
{ protected:
char *pstr;
public:
CStrOne( char str[ ])
{ pstr=str;
}
void show()
{ cout<<"strings="<<pstr<<endl;
}
};
class CStrTwo:public CStrOne
{
char *newpstr;
public:
CStrTwo( char str1[ ],char str2[ ]):CStrOne(str1)
{ newpstr=str2;
}
void show()
{ cout<<"strings1="<<pstr<<endl;
cout<<"strings2="<<newpstr<<endl;
}
void joint()
{ char temp[100];
strcpy(temp, pstr);
newpstr=strcat(temp,newpstr);
cout<<newpstr<<endl;
}
};
void main()
{
CStrTwo str("My Name is Lian",", 45 years old");
str.show();
str.joint();
}
为什么程序1里来的p1和p2使用时要开内存空间,而程序2pstr赋值不用开内存空间?