您好,我对某些代码有疑问。
该代码是否可以像这里一样正常工作?

我以为我需要使用#include cstring

我问我的老师,他告诉我代码是正确的,并且
它应该与#include字符串一起使用

它是否正确?有人可以解释一下吗?谢谢。

#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 ;
}

最佳答案

简而言之,该程序可能会编译,也可能不会编译。如果需要<cstring>函数,则需要包括strcpy()(如@ user4581301的注释中所指出。

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

10-06 08:14