C++的问题

majia041

新手上路
注册
2003-04-14
消息
106
荣誉分数
0
声望点数
0
#include <iostream.h>
#include <string.h>

class pp
{
public:
pp(char * te = "noname") : name(new char[strlen(te)+1]){strcpy(name,te);}
pp(const pp & p) : name(new char[strlen(p.name)+1]){strcpy(name,p.name);}
pp & operator = (const pp & p)
{
if (this != &p)
{
strcpy(name, p.name);
}
return *this;
}
~pp(){
delete [] name;
}
void getname(){cout<<name<<endl;}
private:
char * const name;
};

void main()
{
pp p("is"), p2;
pp p1 = p;
p2 = p1;
p2.getname ();
p1.getname ();
}

上面这段程序能编译和运行。根据下面那个XD的提示,我改了下程序,另外把“=”加上去了。我想知道当有char * const name时,COPY CONSTRUTOR和“=”写成这样有没有问题。或者有其他潜在的问题。
 
In copy constructor, string name is dynamically allocated. No
destructor. Name is not cleaned anywhere. This is memory leak.
 
后退
顶部