运算符过载<<问题

Problems overloading << operator

本文关键字:lt 问题 运算符      更新时间:2023-10-16

我在重载<<运算符时遇到了一些问题。错误是这样的:"JSON"不是从"const std::basic_string<_CharT,_Traits,_Alloc>"派生的。

如何使操作员<<过载的正确方法。我的目标是能够做std::cout<<p>我的代码是:主.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;
}
编译器

在看到函数调用时仅考虑以前见过的函数,因此它看不到您在.cpp文件中拥有的operator<<

您必须在某处放置operator<<的前向声明,以便编译器知道它,如标头所示:

std::ostream& operator<<(std::ostream&, const JSON&);

然后编译器在看到你调用该函数时会知道它。

你需要在类JSON的声明之后,在JSON.hpp中提供ostream& operator<<的声明:

// JSON.hpp
....
class JSON
{
  // as before
};
std::ostream& operator<<(std::ostream& out, const JSON& json);

operator<<的声明需要可供main使用。将其放入头文件中。