这段代码的输出是什么,它在构造函数中使用 strcpy?

what would be the output of this code, it uses strcpy in a constructor?

本文关键字:构造函数 strcpy 是什么 段代码 代码 输出      更新时间:2023-10-16

您好,我对一些代码有疑问。 此代码是否支持按此处工作?

我以为我需要使用 #include 串

我问我的老师,他告诉我代码很好,而且 它应该与 #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 ;
}

简而言之,"按原样",程序可能会也可能不会编译。如果需要strcpy()函数,则需要包含<cstring>(如@user4581301注释中所述)。

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

TL;博士

使用比<string><cstring>,但即使更正了标头,程序也没有输出。

讨论

我以为我需要使用 #include 字符串

我问了我的老师,他告诉我代码很好,它应该与字符串一起使用 #include

你以为对,老师想错了1.C++标准不保证通过包含<string>来提供strcpy

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

2有时你会发现一个标头,您希望包含另一个标头,而不是 forward 声明另一个标头所需的部分,以避免包含另一个标头的编译时开销。

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

#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");

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