C++ 超载<&书信电报;输出映射的键类型和映射类型
我有一个课程目录类,它有一个类型为C++ 超载<&书信电报;输出映射的键类型和映射类型,c++,operator-overloading,C++,Operator Overloading,我有一个课程目录类,它有一个类型为map Courses的私有变量。我想重载来存储整个目录,重载您自己的类的操作符,而不是映射或字符串 例如: std::ostream& operator<<(std::ostream& os, const YourClass& catalog) { for (const auto& entry: catalog.Courses) { os << entry.first &l
map Courses
的私有变量。我想重载来存储整个目录,重载您自己的类的操作符,而不是映射或字符串
例如:
std::ostream& operator<<(std::ostream& os, const YourClass& catalog)
{
for (const auto& entry: catalog.Courses)
{
os << entry.first << " " << entry.second << '\n';
}
return os;
}
您的目录现在将是一个std::map
,您可以重载来存储整个目录,重载自己类的操作符,而不是映射或字符串
例如:
std::ostream& operator<<(std::ostream& os, const YourClass& catalog)
{
for (const auto& entry: catalog.Courses)
{
os << entry.first << " " << entry.second << '\n';
}
return os;
}
您的目录现在将是一个std::map
,您可以重载在课程[“TMA4100”]
和“TMA4100”
之间没有任何连接,只需std::map有什么问题吗?难道您忘了在operator@Garf365是的,我知道。我的问题主要是关于参数。地图之外的课程[“TMA4100”]
和课程“TMA4100”
之间没有任何联系。仅仅std::难道你忘了在operator@Garf365是的,我知道。我的问题主要是关于参数。哦,天哪。我不敢相信我在课堂上没有超载…那太愚蠢了,谢谢你指出这一点。顺便说一句,你能解释一下for循环是如何工作的吗?我以前没见过“自动”。@Auclair它是一个C++11“基于范围”的循环。它相当于(std::map::const_iterator entry=catalog.Courses.begin();entry!=catalog.Courses.end();++entry)
,但更好auto
是一个C++11特性,它让编译器为您推断类型。哇,这看起来很复杂。谢谢你的帮助。有没有可能让它过载,这样我就可以通过目录[“TMA4100”]
并将该课程写入文件,而不是一次性将整个目录写入文件?毫无疑问,你的方法更流畅,但我只想学习:)@Auclair我在答案中添加了一些建议。哦,我的天啊。我不敢相信我在课堂上没有超载…那太愚蠢了,谢谢你指出这一点。顺便说一句,你能解释一下for循环是如何工作的吗?我以前没见过“自动”。@Auclair它是一个C++11“基于范围”的循环。它相当于(std::map::const_iterator entry=catalog.Courses.begin();entry!=catalog.Courses.end();++entry)
,但更好auto
是一个C++11特性,它让编译器为您推断类型。哇,这看起来很复杂。谢谢你的帮助。有没有可能让它过载,这样我就可以通过目录[“TMA4100”]
并将该课程写入文件,而不是一次性将整个目录写入文件?毫无疑问,你的方法更流畅,但我只想学习:)@Auclair我在答案中添加了一些建议。
struct CourseInfo
{
std::string name;
std::string description;
StaffMember teacher;
// ... more useful stuff ...
};
std::ostream& operator<<(std::ostream& os, const CourseInfo& info)
{
os << info.name << " " << info.description << " " << info.teacher;
return os;
}
YourClass catalog;
// ... populate the catalog
std::cout << catalog.courseInfo("TM4100") << std::endl;