gpt4 book ai didi

c++ - 重载 << 运算符的问题

转载 作者:行者123 更新时间:2023-11-28 03:28:01 24 4
gpt4 key购买 nike

我在重载 << 运算符时遇到了一些问题。错误是这个:'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;
}

最佳答案

编译器在看到函数调用时只考虑它之前看到的函数,所以它看不到 operator<<你在 .cpp 文件中。

您必须提前声明您的 operator<<某个地方让编译器知道它,比如在标题中:

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

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

关于c++ - 重载 << 运算符的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13417871/

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