运算符过载<<问题
Problems overloading << operator
我在重载<<运算符时遇到了一些问题。错误是这样的:"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
使用。将其放入头文件中。
相关文章:
- 警告处理为错误这里有什么问题
- 最小硬币更换问题(自上而下方法)
- 为"adjacent"变量赋值时出现问题
- 我的神经网络不起作用 [XOR 问题]
- 在Ubuntu 16.04上安装Cilk时出现问题
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 编译包含字符串的代码时遇到问题
- Project Euler问题4的错误解决方案
- 问题:什么是QAbstractItemView::NoEditTriggers的反面
- 在编译C++代码(具有dlib和opencv)到WASM时面临问题
- 在进程中对同一管道进行读取和写入时C++管道出现问题
- 静态数据成员的问题-修复链接错误会导致编译器错误
- C++ 雷神库 - 使用资源加载器类时出现问题(不命名类型)
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 一个关于在C++中重载布尔运算符的问题
- 首要问题的答案让值班员搞错了
- setlocale的C++土耳其字符串问题
- 如何重构类层次结构以避免菱形问题
- 呼叫运营商<<临时
- 基于boost的程序的静态链接——zlib问题