文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>C++中的初始化与赋值

C++中的初始化与赋值

时间:2011-05-24  来源:Mr.Late

永远不要对一个未被初始化的存储区执行用户自定义的赋值操作,且看:

 1 #include <stdio.h>
2 #include <string.h>
3
4 class String{
5 public:
6 String(const char *init){
7 if(!init) init = "";
8 s_ = new char[strlen(init) + 1];
9 strcpy(s_,init);
10 }
11 ~String(){
12 delete [] s_;
13 }
14 String &operator=(const char *str){
15 if(!str) str = "";
16 char *tmp = strcpy(new char[strlen(str) + 1],str);
17 if(!s_)
18 printf("s_ is NULL, you cannot delete it!\r\n");
19 delete [] s_;
20 s_ = tmp;
21 return *this;
22 }
23 private:
24 char *s_;
25 };
26 int main(int argc, char **argv)
27 {
28 String *names = static_cast<String *>(::operator new(100));
29 names[0] = "Sakamoto";
30 // it is very likely that you get a weird output!
31 printf("The value of names is :%s\n",names);
32 return 0;
33 }
相关阅读 更多 +
排行榜 更多 +
哥布林弹球b服手游下载

哥布林弹球b服手游下载

休闲益智 下载
小马样式盒游戏下载

小马样式盒游戏下载

休闲益智 下载
异变小镇中文版下载安装

异变小镇中文版下载安装

冒险解谜 下载