0
我创建了我的类file
,它是std::ofstream
的包装。我创建了一个Container
来包含所有file
的实例。将流的实例插入容器
class file
{
private:
std::ofstream ofs;
public:
void open(std::string filename);
void write(std::string s);
void close();
};
class Container
{
private:
std::map<int, file> m;
public:
void insert(file f,int i)
{
m.insert(std::pair<int,file> (i,f));
}
void get(int i)
{
m.at(i);
}
};
但是,这个代码有问题。在insert
方法中,我试图复制std::pair<int,file>
,这是因为std::ofstream
的复制构造函数被删除而无法完成(请参阅下面的编译错误)。
我想在容器中连续添加file
的实例。我怎样才能做到这一点?
以下是编译错误
In file included from src/test.cpp:1:
In file included from /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/iostream:38:
In file included from /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/ios:216:
In file included from /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/__locale:15:
In file included from /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/string:439:
In file included from /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/algorithm:627:
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/utility:274:23: error: call to implicitly-deleted copy constructor of
'file'
: first(__x), second(__y) {}
^ ~~~
src/test.cpp:35:22: note: in instantiation of member function 'std::__1::pair<int, file>::pair' requested here
m.insert(std::pair<int,file> (i,f));
^
src/test.cpp:9:21: note: copy constructor of 'file' is implicitly deleted because field 'ofs' has a deleted copy constructor
std::ofstream ofs;
^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/fstream:1168:5: note: copy constructor is implicitly deleted because
'basic_ofstream<char, std::__1::char_traits<char> >' has a user-declared move constructor
basic_ofstream(basic_ofstream&& __rhs);
^
1 error generated.
如何在主代码中调用'Container :: insert'方法? – Holt
我没有意识到这很重要。 'Container'是一个单身人士,我使用'MyContainer.insert(文件,索引)'。 –
你如何创建你插入的'file'?你想复制一份还是放入'Container'?你能告诉我们一个典型的'文件'创建和插入容器内的例子吗? – Holt