【问题标题】:what would be the output of this code, it uses strcpy in a constructor?这段代码的输出是什么,它在构造函数中使用 strcpy?
【发布时间】:2019-09-01 12:20:18
【问题描述】:

您好,我对一些代码有疑问。 这段代码可以在这里工作吗?

我认为我需要使用#include cstring

我问了我的老师,他告诉我代码是好的,而且 它应该与#include string

一起使用

这是正确的吗?有人可以解释一下吗?谢谢。

#include <iostream>
#include <string> //strcpy() works with string?
using namespace std;

class libraryBook{

  private:

    char title [80]; //cstring
    int available;

  public:

    libraryBook(char initTitle[]);//cstring as argument

};


libraryBook::libraryBook(char initTitle[]){

  strcpy(title, initTitle); 
  available = 1;

}


int main() {

  libraryBook b1 ("computing"); //what would be the output without changing the code ?

  return 0 ;
}

【问题讨论】:

  • 既然你在 C++ 中,为什么不用std::string 而不是char 的数组呢?
  • 我想你想要#include &lt;cstring&gt;,而不是#include &lt;string&gt; 得到strcpystrcpy 是一个很好的 ol' C 函数,所有 ol' C 的东西都在以 c 开头的标题中
  • 如果要复制字符串字面量`.copy()'就是函数
  • 就像@user4581301 说的,strcpynot in <string>
  • 旁注:libraryBook(char initTitle[]); 将像libraryBook(const char *initTitle); 一样多才多艺,您将能够安全且无错误地使用字符串文字。在现代标准 C++ 中,libraryBook b1 ("computing"); 是完全非法的,以防止您意外写入只读存储。

标签: c++ class c-strings strcpy


【解决方案1】:

简而言之,“按原样”,程序可能编译也可能不编译。如果您想要 strcpy() 函数,则需要包含 &lt;cstring&gt;(正如 @user4581301 在 cmets 中指出的那样。

在包含&lt;cstring&gt; 之后,程序的输出什么都没有,因为您没有打印任何内容。但实际上,您不应该在 C++ 中使用字符数组代替 std::string。可以在here 找到您的代码演示。

【讨论】:

  • 有趣的是,答案往往会同时弹出,即使是在提出问题几个小时后。
  • @user4581301 我向你保证这纯属巧合:)
【解决方案2】:

TL;DR

使用&lt;cstring&gt; 而不是&lt;string&gt;,但是即使更正了标头,程序也没有输出。

讨论

我认为我需要使用#include cstring

我问过我的老师,他告诉我代码很好,应该可以使用#include string

你想对了,老师错了1C++ Standard 不保证 strcpy 通过包含 &lt;string&gt; 可用。

1 有点错误。不能保证&lt;string&gt; 提供strcpy 或最终包含&lt;cstring&gt; 的标头链,但没有人说它不能。只是不要指望它。文件应始终包含它需要的所有标题2 以防止可避免的错误。当老师告诉你你的代码是正确的时,他们的大脑也可能被他们的大脑愚弄到看到没有 c 的 c。他们可能打算让您使用旧的 C 标头 &lt;string.h&gt;。很难说。

2 有时你会发现一个头文件你希望包含另一个头文件而不是 forward declares 另一个头文件的部分,它需要避免包含其他标题。

【讨论】:

    【解决方案3】:

    至少在我看来,你老师的想法显然更好。一个合理的起点应该是这样的:

    #include <string>
    
    class LibraryBook { 
        std::string name;
        int available;
    public:
        LibraryBook(std::string const &name, int available = 1) 
            : name(name)
            , available(available) 
        {}
    };
    

    然后创建一本书看起来像这样:

    LibraryBook book("Steal This Code");
    

    由于我们没有包含任何代码来写出任何内容,因此不会产生任何输出(除了返回表示成功退出的代码)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-02
      • 2012-02-17
      • 1970-01-01
      相关资源
      最近更新 更多