---
title: "c和c++的转换-1"
author: "1000copy"
date: "2011-04-08T21:15:00Z"
tags: []
categories: ["编程语言"]
slug: "c-c-1"
draft: false
lastmod: "2011-04-08T21:16:24Z"
id: 993377
url: "https://1000copy.iteye.com/blog/993377"
---

用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 ;
}
```

 

这样就很简单直接了。