字符串类型在 C++ 中的 strcpy() 中

string type in strcpy() in C++

本文关键字:strcpy 中的 类型 C++ 字符串      更新时间:2023-10-16
#include <iostream>
#include <string>
using namespace std;
int main() {
    char a[10];
    string b = "Hello"; 
    char c[] = "Hello";
    char *d = "Hello";
    strcpy(a, b); // compiler complains.
    strcpy(a, c);
    strcpy(a, d);
}

我知道 strcpy 被定义为

char * strcpy ( char * destination, const char * source );

但是如果string类型变量与char*char[]相同,为什么string类型的内容不能复制到char[]

std::string

字符数组不同。 它是一个C++对象。 如果要以 C 字符串的形式访问它,请调用其 c_str() 方法:

strcpy(a, b.c_str());