#include <iostream>
#include <fstream>
using namespace std;
int main () {
ofstream fout = ofstream("fout.txt");
}
此代码使用 rgbkrk 的脚本包(使用 g++)在 atom 中编译得很好,但是当我尝试使用 g++ 在终端上编译它时,我得到以下输出。不确定我做错了什么。
$ g++ test.cpp -o hw
In file included from test.cpp:1:
In file included from /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/iostream:39:
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/streambuf:493:64: error:
base class 'std::__1::ios_base' has private copy constructor
_LIBCPP_EXTERN_TEMPLATE(class _LIBCPP_EXTERN_TEMPLATE_TYPE_VIS basic_ios<char>)
^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/iosfwd:147:32: note:
in implicit copy constructor for 'std::__1::basic_ios<char>' first
required here
class _LIBCPP_TEMPLATE_VIS basic_ofstream;
^
test.cpp:6:19: note: in implicit copy constructor for
'std::__1::basic_ofstream<char, std::__1::char_traits<char> >' first
required here
ofstream fout = ofstream("fout.txt");
^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/ios:313:5: note:
declared private here
ios_base(const ios_base&); // = delete;
^
1 error generated.
最佳答案
首先,这实际上不是 GCC。我知道它看起来像,因为你执行了 g++
,但输出表明你在 macOS 上,而在 macOS 上 g++
实际上是变相的 Clang。是的,这很愚蠢。
其次,在 C++17 之前,您不能像流那样对不可复制的事物使用复制初始化。尽管经常省略多余的拷贝,但它们始终是可能的。
所以,而不是:
ofstream fout = ofstream("file.txt");
你应该写一个简单的声明:
ofstream fout("file.txt");
或:
ofstream fout{"file.txt"};
(新)
在 C++17 中,规则发生了变化,省略现在是强制性,并且不再要求假设拷贝是可能的。因此,在 C++17 模式下,您的代码应该可以工作。
您的手动 g++
调用不包含任何用于打开 C++17 模式的开关,这显然不是您的 Clang 版本的默认设置。
始终明确指定所需的语言标准版本。我的首选命令是:
g++ -Wall -Wextra -pedantic -std=c++17 test.cpp -o hw
关于c++ - 在 atom 中编译但不在终端中编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59093923/