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

标签 c++ save operator-overloading ostream

我创建了一个测试类,它有一个公共(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/

相关文章:

c++ - 运算符未解析为运算符函数 c++

types - 递归实现特征 "Not"

c++ - 插入节点时对链表进行排序

python - 使用Python中的列表以特定方式写入文本文件

intellij-idea - 按 Ctrl-S 时,IntelliJ IDEA 光标移动到行首

c++ - 如何优先选择 `operator<<` 而不是通用 `operator T()` 转换?

c++ - 究竟什么数据结构是 C++ 中的双端队列?

java - 调试混合 C++ 和 Java 代码的实用方法

c++ - 为什么 CoCreateInstance 可以在完全相同的上下文中返回两个不同的 HRESULT?

java - 保存动态创建的按钮android