我有一个具有addString
和addInteger
等功能的对象。这些函数将数据添加到JSON字符串。最后,可以获取并发送JSON字符串。如何通过重载下标运算符来实现以下功能,从而使这更容易?
jsonBuilder builder();
builder[ "string_value" ] = "Hello";
builder[ "int_value" ] = 5;
builder[ "another_string" ] = "Thank you";
答案 0 :(得分:1)
您需要具有operator[]
函数返回的代理类,该类处理分配。然后,代理类重载赋值运算符以不同方式处理字符串和整数。
这样的事情:
#include <iostream>
#include <string>
struct TheMainClass
{
struct AssignmentProxy
{
std::string name;
TheMainClass* main;
AssignmentProxy(std::string const& n, TheMainClass* m)
: name(n), main(m)
{}
TheMainClass& operator=(std::string const& s)
{
main->addString(name, s);
return *main;
}
TheMainClass& operator=(int i)
{
main->addInteger(name, i);
return *main;
}
};
AssignmentProxy operator[](std::string const& name)
{
return AssignmentProxy(name, this);
}
void addString(std::string const& name, std::string const& str)
{
std::cout << "Adding string " << name << " with value \"" << str << "\"\n";
}
void addInteger(std::string const& name, int i)
{
std::cout << "Adding integer " << name << " with value " << i << "\n";
}
};
int main(int argc __attribute__((unused)), char *argv[] __attribute__((unused)))
{
TheMainClass builder;
builder[ "string_value" ] = "Hello";
builder[ "int_value" ] = 5;
builder[ "another_string" ] = "Thank you";
}
答案 1 :(得分:0)
我认为你最终需要这个。我已经实现了获取字符串输入,对整数执行相同操作。
#include <iostream>
#include <string>
#include <map>
class jsonBuilder
{
public:
std::map<std::string,std::string> json_container;
std::string& operator[](char *inp)
{
std::string value;
json_container[std::string(inp)];
std::map<std::string,std::string>::iterator iter=json_container.find(std::string(inp));
return iter->second;
}
};
int main()
{
jsonBuilder jb;
jb["a"]="b";
std::map<std::string,std::string>::iterator iter=jb.json_container.find(std::string("a"));
std::cout<<"output: "<<iter->second;
}