在构造函数中使用new时的注意事项

果然,光看书是没用的,一编程序,很多问题就出现了--
注意事项: 1、 如果构造函数中适用了new初始化指针成员,则构析函数中必须要用delete
2、 new与delete必须兼容,new对应delete,new[]对应delete[]
3、如果有多个构造函数,则必须以相同的方式使用new,要么都是new,要么都是new[],因为构析函数只能有一个
4、 应该定义一个复制构造函数,通过深度复制,将一个对象初始化为另一个对象
5、 应该定义一个赋值运算符,通过深度复制,将一个对象复制给另一个对象 #include<iostream>
#include<cstring>
#include<fstream>
using namespace std;
class String
{
private:
char *str;
int len;
static int num_string; public:
String();
String(const char *s);
String(const String &s);
~String();
friend ostream& operator<<(ostream &os,String s);
String operator=(const String &s)
{
if(this==&s) return *this; len=s.len;
delete [] str;
str=new char[len+1];
strcpy(str,s.str);
return *this;
}
};
int String::num_string=0;
String::String()
{
len=4;
str=new char[len+1];
strcpy(str,"C++");
num_string++;
}
String::String(const char *s)
{
len=strlen(s);
str=new char[len+1];
strcpy(str,s);
num_string++;
}
String::String(const String &s)
{
len=s.len;
num_string++;
str=new char[len+1];
strcpy(str,s.str);
}
String::~String()
{
num_string--;
delete [] str;
printf("--- %d\n",num_string);
}
ostream& operator<<(ostream &os,String s)
{
os<<s.str;
return os;
}
int main()
{
String p("wwwww");
String p1("qqqqqq");
String p2;
p2=p1;
cout<<p<<endl<<p1<<endl<<p2<<endl;
return 0;
}

  

上一篇:python opencv 检测特定颜色


下一篇:fuzhou 1075 分解素因子