`
1000copy
  • 浏览: 72506 次
  • 性别: Icon_minigender_1
  • 来自: 成都
文章分类
社区版块
存档分类
最新评论

c和c++的转换-1

阅读更多

用c连接字符串还是比较麻烦的。因为string并非c的内置类型。我们看看麻烦的情况。以连接字符串为例:

 

c的代码是这样的:

 

 

char * strcat_cstyle()
{
     // c++ style
    char* a ="hello ";
    char* b ="world by c";
    int len = strlen(a)+strlen(b)+1;
    char*c =(char*)malloc(len);
    memset(c,0,len);
    strcat(c,a);
    strcat(c,b);
    return c;
}
 

你需要

 

  • 自己计算新字符串的长度
  • 自己分配并转型
  • 自己清空内存区
  • 然后连接
  • 别忘了,用完后记得free

不这样会如何?你可以试试吧len改小,看看c遇到这样的问题的反应会如何暴烈。

 

还好,在c++内虽然没有string类型,但是在库内提供了一个string的类,于是:

 

 

 

string strcat_cppstyle()
{
     // c++ style
    string a ="hello";
    string b ="world by c++";
    return a+b ;
}
 

这样就很简单直接了。

 

 

 

0
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics