【发布时间】:2013-11-25 13:06:22
【问题描述】:
在我的应用程序中,我有一个包含另一个类的向量的类,我无法为此编写重载的 YAML::Emitter& 运算符
为了说明,我编写了重现错误的波纹管文件:
Department 类包含 Employee 的向量,我需要以 Yaml 格式输出包含所有员工的 Department。
我收到以下奇怪的错误,似乎与我的方法签名不匹配:
$ g++ ta.cpp -L ~/yaml-cpp/lib/ -I ../Thanga/yaml/yaml-cpp-0.5.1/include/ -lyamlcpp 2>&1|更多 ... ta.cpp:37:16: 注意:YAML::Emitter& 运算符没有已知的参数 2 从“const Employee”到“Department&”的转换 ta.cpp:28:16: 注意:YAML::Emitter& 运算符没有已知的参数 2 从“const Employee”到“Employee&”的转换
这是完整的源文件:
#include <iostream>
#include <fstream>
#include "yaml-cpp/yaml.h"
#include <cassert>
#include <vector>
#include <string>
struct Employee
{
std::string name;
std::string surname;
int age;
std::string getName(){return name;}
std::string getSurname(){return surname;}
int getAge(){return age;}
};
struct Department
{
std::string name;
int headCount;
std::vector<Employee> staff;
std::string getName(){return name;}
int getHeadCount(){return headCount;}
std::vector<Employee> & getStaff(){return staff;}
};
YAML::Emitter& operator << (YAML::Emitter& out, Employee& e) {
out << YAML::BeginMap;
out << YAML::Key <<"name"<<YAML::Value <<e.getName();
out << YAML::Key <<"surname"<<YAML::Value <<e.getSurname();
out << YAML::Key <<"age"<<YAML::Value <<e.getAge();
out << YAML::EndMap;
return out;
}
YAML::Emitter& operator << (YAML::Emitter& out, Department& d) {
out << YAML::BeginMap;
out << YAML::Key <<"name"<<YAML::Value <<d.getName();
out << YAML::Key <<"headCount"<<YAML::Value <<d.getHeadCount();
out << YAML::Key <<"Employees"<<YAML::Value <<d.getStaff();
out << YAML::EndMap;
return out;
}
int main()
{
Employee k;
Department d;
d.name="Twidlers";
d.headCount=5;
k.name="harry";
k.surname="person";
k.age=70;
d.staff.push_back(k);
k.name="joe";
k.surname="person";
k.age=30;
d.staff.push_back(k);
k.name="john";
k.surname="doe";
k.age=50;
d.staff.push_back(k);
std::ofstream ofstr("output.yaml");
YAML::Emitter out;
out<<d;
ofstr<<out.c_str();
}
【问题讨论】:
标签: c++ vector operator-overloading yaml-cpp