这段代码即使在 C++11 标准下使用 minGW 编译器也能正常工作:
#include <iostream>
int main(int argc, char const *argv[])
{
printf("haha");
return 0;
}
为什么要这样做?我没有包含 stdio.h
但我可以使用 printf()
和 rand()
之类的函数。它们是否包含在 iostream
中?至少我没有发现它们包括在内。如果你说它包含在 iostream
中,请给我看证据。
最佳答案
它的实现定义了它是否有效。
该实现可能包含它需要的其他 header ,但作为开发人员的您不应依赖它,并且也包含 cstdio
,这是访问 std::printf
的保证方式。
包含 stdio.h
会将 printf
放在全局命名空间中,这在 C++ 中通常不是人们想要的,所以坚持使用 cstdio
。
看来您的实现将 printf
放在全局命名空间中,即使您只包含了一个 C++ 头文件。这很不幸,但这种情况也会发生。
证据:我的预处理器叫做 cpp
,我可以用它来列出包含的头文件。我有一个名为 std.cpp
的程序:
#include <iostream>
int main() {}
如果我使用 cpp
列出包含标题的一小部分cpp -M std.cpp | tr -d '\\' | tr ' ' '\n' | \
grep -E '^/[^\.]+$' | awk -F/ '{print $NF}'
我在我的系统 上得到了这些 C++ 头文件 :iostream
ostream
ios
iosfwd
cwchar
exception
typeinfo
new
type_traits
cstdint
clocale
cctype
string
initializer_list
cstdlib
cstdio
cerrno
system_error
stdexcept
streambuf
cwctype
istream
是的, cstdio
就在那里,其中还包括 stdio.h
。
关于c++ - 为什么在包含 iostream 时可以使用 printf()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62533672/