gpt4 book ai didi

c++ - 重载 fstream << 运算符以保存 "any"种数据

转载 作者:行者123 更新时间:2023-11-28 00:16:13 25 4
gpt4 key购买 nike

我创建了一个测试类,它有一个公共(public)变量double x。我已经重载了 ostream << 运算符,以便能够打印出变量 x。我还编写了一个外部 save(filename, object) 函数,它将以特定方式保存对象的内容。我想使用 << 运算符将 x 的内容保存到文件中。头文件 (TestH.hpp) 如下所示:

#ifndef TESTH_HPP_
#define TESTH_HPP_

#include <iostream>
#include <fstream>
#include <string>


class Test {
public:
double x;
friend std::ostream& operator << (std::ostream& os, Test& p);
inline Test();
inline virtual ~Test();
};

inline std::ostream& operator << (std::ostream& os, Test& p);
template <class V>
inline void save(const std::string& pname, const V& data);

#endif /* TESTH_HPP_ */

这是定义函数的文件(TestC.cpp):

#ifndef TESTC_CPP_
#define TESTC_CPP_

#include "TestH.hpp"

Test::Test() {
x=10;
}

Test::~Test() {}

std::ostream& operator << (std::ostream& os, Test& p) {
// Output to screen
os << "Test:\t";
os << p.x;
return os;
}

template <class V>
void save(const std::string& pname, const V& data) {
std::ofstream myfile;
myfile.open(pname.c_str());
myfile << data;
myfile.close();
std::cout << "====== File is saved! ======\nPathname: " << pname << std::endl;
}

#endif /* TESTC_CPP_ */

最后是测试保存功能的代码 (Test.cpp):

#include <iostream>
#include "TestC.cpp"

int main () {
std::string fn = "test.txt";
int i=1;
Test a;

// std::cout << a;
save(fn,a);
return 0;
}

我得到了一个很长的错误列表,但基本上是说在 TestC.cpp 代码中,编译器无法执行 myfile << data; 命令:

In file included from ../Test.cpp:3:0:
../TestC.cpp:33:9: note: ‘const Test’ is not derived from ‘const std::basic_string<_CharT, _Traits, _Alloc>’
myfile << data;

你能帮我解决这个问题吗?感谢您的宝贵时间。

最佳答案

您正在通过非常量引用流式传输测试:

friend std::ostream& operator << (std::ostream& os, Test& p);

您想通过 const 引用流式传输它:

friend std::ostream& operator << (std::ostream& os, const Test& p);
^^^^^^

错误是因为当您从 save() 调用它时,您传入了一个常量引用:

template <class V>
void save(const std::string& pname, const V& data) {
...
myfile << data; // <== data is const Test&
...
}

关于c++ - 重载 fstream << 运算符以保存 "any"种数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30171012/

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