std::strcpy 和 std::strcat 带有 std::string 参数

std::strcpy and std::strcat with a std::string argument

这是来自 C++ Primer 第 5 版。 “largeStr 的大小”是什么意思? largeStrstd::string 的实例,所以它们具有动态大小?

我也不认为代码可以编译:

#include <string>
#include <cstring>

int main()
{
    std::string s("test");
    const char ca1[] = "apple";
    std::strcpy(s, ca1);
}

我是不是漏掉了什么?

你错过了

char largeStr[100];

或类似的书没有提到。

你应该做的是快速忘记 strcpy 和 strcat 以及 C-style 字符串。只要记住如何用它们制作 C++ std::string 并且永远不要回头看。

strcpystrcat 仅对 C 字符串进行操作。该段落令人困惑,因为它描述但未明确显示 manually-sized C 字符串。为了编译第二个片段,largeStr 必须与第一个片段中的变量不同:

char largeStr[100];

// disastrous if we miscalculated the size of largeStr
strcpy(largeStr, ca1);        // copies ca1 into largeStr
strcat(largeStr, " ");        // adds a space at the end of largeStr
strcat(largeStr, ca2);        // concatenates ca2 onto largeStr

如第二段所述,largeStr这里是一个数组。数组具有在编译时确定的固定大小,因此我们不得不选择一些任意大小,例如 100 我们希望它足够大以容纳结果。但是,这种方法“充满了严重错误的可能性”,因为 strcpystrcat 强制执行 100 的大小限制。

Also I don't think the code compiles...

同上,把s改成数组就可以编译了

#include <cstring>

int main()
{
    char s[100] = "test";
    const char ca1[] = "apple";
    std::strcpy(s, ca1);
}

请注意,我没有写 char s[] = "test";。为 "apple" 保留额外的 space 很重要,因为它比 "test".