在我的应用程序中,我有一个包含另一个类的向量的类,我无法编写重载的YAML :: Emitter&运营商LT;<对此。
为了说明,我写了一个再现错误的波纹管文件:
类部门包含一个Employee向量,我需要以Yaml格式输出所有员工的部门。
我得到以下奇怪的错误,似乎与我的方法签名不匹配:
$ g ++ ta.cpp -L~ / yaml-cpp / lib / -I ../Thanga/yaml/yaml-cpp-0.5.1/include/ -lyamlcpp 2>& 1 | more ... ta.cpp:37:16:注意:YAML :: Emitter&运算符<<(YAML :: Emitter&,Department&) ta.cpp:37:16:注意:没有已知的从'const Employee'到'Department&'的参数2的转换 ta.cpp:28:16:注意:YAML :: Emitter&运算符<<(YAML :: Emitter&,Employee&) ta.cpp:28:16:注意:没有已知的从'const Employee'到'Employee&'的参数2的转换
以下是完整的源文件:
#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();
}
答案 0 :(得分:0)
为vector
提供的重载需要const std::vector<T>&
,因此您必须在整个过程中额外添加const
个字段:
YAML::Emitter& operator << (YAML::Emitter& out, const Employee& e)
...
YAML::Emitter& operator << (YAML::Emitter& out, const Department& d)
然后将它们放在你的成员函数上,例如:
const std::vector<Employee>& getStaff() const { return staff; }
(一般情况下,你应该默认使你的getter const,如果你需要改变状态,添加setter而不是非const getter。)