文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
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 }
相关阅读 更多 +
排行榜 更多 +
冲破牢笼手机版

冲破牢笼手机版

飞行射击 下载
街头足球安卓版

街头足球安卓版

体育竞技 下载
火柴人特别行动

火柴人特别行动

体育竞技 下载