gpt4 book ai didi

c++ - 尝试使用 ostream 保存文件内容时出错

转载 作者:行者123 更新时间:2023-11-27 23:40:24 24 4
gpt4 key购买 nike

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

编译错误如下

In member function 'void CDemoMap::saveFile(std::__cxx11::string&)': ..\src\VerifyProgram.cpp:51:9: error: no match for 'operator<<' (operand types are 'std::ostream {aka std::basic_ostream}' and 'std::ostream {aka std::basic_ostream}') cout << print(coutFile)

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

#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;
}

最佳答案

在 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) Returns a null pointer if fail() returns true, otherwise returns a non-null pointer. This pointer is implicitly convertible to bool and may be used in boolean contexts.

2) Returns true if the stream has no errors and is ready for I/O operations. Specifically, returns !fail().

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

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

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

关于c++ - 尝试使用 ostream 保存文件内容时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55556995/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com