【问题标题】:Error when try to save the content of a file using ostream尝试使用 ostream 保存文件内容时出错
【发布时间】:2019-04-07 08:22:05
【问题描述】:

我用 C++ 编写了一个程序并使用 gcc 7.3 编译它。这是一个将字符串写入文件的简单程序。 但是只有在使用 gcc 7.3 编译时才会产生编译器错误。使用旧的 4.8.5 编译器成功编译程序。

编译错误如下

在成员函数'void CDemoMap::saveFile(std::__cxx11::string&)'中: ..\src\VerifyProgram.cpp:51:9: 错误: 'operator

有谁能帮我解决这个问题吗? 代码如下

#include <map>
#include <iostream>
#include <ostream> 

#include <fstream>
using namespace std;
class CDemoMap
{
    public:
     map<int,int> m_sMap;
    void saveFile(std::string &);
    std::ostream& print(std::ostream  &s);
};


std::ostream& operator << (ostream& s, const CDemoMap &m)
{
   if (m.m_sMap.size())
   {
      s << "-----------------\nSOCKET FQDN MAP\n-----------------\n";
      s << "fqdn                    host:port              timestamp\n";

      for (map<int,int>::const_iterator iter = m.m_sMap.cbegin(); iter != 
           m.m_sMap.cend(); ++iter)
      {
         s << iter->first << "   " << (iter->second);
      }
      s << endl;
   }
   return s;
}
std::ostream& CDemoMap::print(std::ostream  &s)
{
   return s << (*this);
}

void CDemoMap::saveFile(std::string & test)
{
   char outFile[50];
   snprintf(outFile, sizeof(outFile), "Data:%s", test.c_str());

   std::ofstream coutFile;

   coutFile.open("Test.txt", std::ios::app);

   cout << print(coutFile);

   coutFile.close();
}


int main() {
    CDemoMap cSocket;
    string str = "Hello";
    cSocket.saveFile(str);
    cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!!
    return 0;
}

【问题讨论】:

  • 当您使用打印选项时,ostream& 的配置似乎需要一个文件
  • 为什么在 4.8.5 编译器中编译?与 7.3.1 相比,4.8.5 编译器不支持 C++11。 ostream 运算符在最新标准中发生了哪些变化?

标签: c++ operator-overloading fstream cout ostream


【解决方案1】:

在 4.8.5 以下行:

 cout << print(coutFile);

翻译成:

 void* v =  print(coutFile);
 std::cout << v;

因为在 C++11 之前有运算符将 ostream 转换为 void* 以检查流是否没有错误 from reference:

operator void*() const;
(1)   (until C++11)
explicit operator bool() const;
(2)   (since C++11)
Checks whether the stream has no errors.

1) 如果 fail() 返回 true,则返回空指针,否则返回 非空指针。此指针可隐式转换为 bool 和 可以在布尔上下文中使用。

2) 如果流没有,则返回 true 错误并准备好进行 I/O 操作。具体来说,返回 !fail()。

从 C++11 开始,代码无法编译,因为转换为 void* 被禁用。

为什么要将返回类型的 print - ostream 传递给另一个 ostream? 它应该是:

print(coutFile); // there is no need to pass ostream to cout

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-22
    • 2014-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多