【发布时间】:2014-02-13 13:30:27
【问题描述】:
如果这是一个完全愚蠢的问题,我很抱歉,但我仍然遇到了麻烦。
我正在尝试将两个std::string fileNames 传递给函数foo,如下所示:
foo(int SomeValue, std::string fileName1, std::string fileName2)
然后我想检查他们是否都有一个文件名长于"",如下所示:
bool hasFile1 = true;
if(fileName1.empty())
{
hasFile1 = false;
}
我的问题出现了,因为我希望能够创建一个 ofstream if hasFile1 == true 和相同的 hasFile2,这两者应该可以在函数 foo 中使用。
我尝试过这样做:
std::ofstream file1;
if(hasFile1)
{
file1 = new std::ofstream(fileName1);
}
但问题在于 file1 是一个不完整的类型。我尝试的另一种方法是
std::ofstream* data;
if(hasFile1)
{
data = new std::ofstream(fileName1)/std::ofstream(fileName1);
}
所有各种组合要么给出不完整类型不允许的错误,要么我无法分配给指针。
问题的重点是如何分配一个ofstream,这样就不需要维护3 个代码块,这些代码块具有ofstreams 的各种组合?
任何帮助将不胜感激!
【问题讨论】:
-
bool hasFile1 = !fileName1.empty();- 无需写 4 行即可。
标签: c++ visual-c++ ofstream