这段代码的输出是什么,它在构造函数中使用 strcpy?
what would be the output of this code, it uses strcpy in a constructor?
您好,我对一些代码有疑问。 此代码是否支持按此处工作?
我以为我需要使用 #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");
由于我们没有包含任何代码来写出任何内容,因此这不会产生任何输出(除了返回指示成功退出的代码)。
- "error: no matching function for call to"构造函数错误
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 为什么在C++中使用私有复制构造函数与删除复制构造函数
- 选择要调用的构造函数
- 如何委托派生类使用其父构造函数?
- 构造函数正在调用一个使用当前类类型的函数
- 没有用于初始化C++中的变量模板的匹配构造函数
- 初始化具有非默认构造函数的std::数组项的更好方法
- 当从函数参数中的临时值调用复制构造函数时
- 在c++构造函数中使用随机字符串生成器
- 一对向量构造函数:初始值设定项列表与显式构造
- 从构造函数抛出异常时如何克服内存泄漏
- 我不明白为什么我声明一个空的内部结构并将其传递给构造函数
- 继承:构造函数,初始化C++11中基类的类C数组成员
- 具有默认模板类型的默认构造函数的类型推导
- 使用dynamic_cast和构造函数时出错
- 这段代码的输出是什么,它在构造函数中使用 strcpy?
- 使用 strcpy 时构造函数中的分段错误