I am getting some problems overloading the << operator.
The error is this one: ‘JSON’ is not derived from ‘const std::basic_string<_CharT, _Traits, _Alloc>’
How is the correct method to overload the operator <<.
My objective is to be able to do std::cout<
My code is:
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;
}
The compiler only considers functions that it has seen before when it sees a function call, so it doesn’t see the
operator<<you have in the .cpp file.You must put a forward declaration of your
operator<<somewhere so the compiler knows about it, like in the header:Then the compiler will know about the function when it sees you call it.