我在重载 << 运算符时遇到了一些问题。错误是这样的:'JSON' 不是从 'const std::basic_string<_CharT, _Traits, _Alloc>' 派生的
重载运算符 << 的正确方法是怎样的?我的目标是能够做到 std::cout<
我的代码是:main.cpp
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include "JSON.hpp"
int main()
{
std::cout<<"JSON V0.1"<<std::endl;
std::string line;
std::ifstream file;
std::stringstream ss;
JSON obj;
file.open("test.json");
if (file.is_open())
{
std::cout<<"File opened"<<std::endl;
ss << file.rdbuf();
obj.parse(ss);
file.close();
}
std::cout<<obj<<std::endl;
return 0;
}
JSON.hpp
#ifndef _JSON_H_
#define _JSON_H_
#include <string>
#include <sstream>
#include <boost/property_tree/ptree.hpp>
class JSON
{
public:
bool parse(std::stringstream &stream);
std::string get(std::string &key);
private:
boost::property_tree::ptree pt;
};
#endif
JSON.cpp
#include <boost/property_tree/json_parser.hpp>
#include "JSON.hpp"
bool JSON::parse(std::stringstream &stream)
{
boost::property_tree::read_json(stream, pt);
return true;
}
std::string JSON::get(std::string &key)
{
std::string rv = "null";
return rv;
}
std::ostream& operator<<(std::ostream& out, const JSON& json)
{
return out << "JSON" << std::endl;
}