如何解决C ++输出向量内容是对象类型
在我的主.cpp
文件中,我有一个保存Band
类型的元素的向量。 Band
是我的implementation.cpp
文件中的结构名称。我的主文件如下所示:
int main(int argc,char* argv[]){
std::vector<Band> bandsVec = readbandFile(argv[1]);
}
对于此行代码,我有一个相应的.h
文件:
struct Band {
std::string bandName;
std::string listofMembers;
};
std::vector<Band> readbandFile(std::string a);
在主文件中,我尝试使用以下增强的for
循环来打印矢量内容:
for (Band band: bandsVec) {
std::cout << band << " ";
}
但是,在使用第一组<<
运算符时出现错误:
没有运算符“
如何打印bandsVec
向量的内容?
解决方法
您需要定义一个重载运算符std::ostream& operator<<(std::ostream&,const Band&);
C ++不知道如何自动打印任何旧结构。例如
std::ostream& operator<<(std::ostream& out,const Band& b)
{
return out << b.bandName << ' ' << b.listOfMembers;
}
如果您知道如何解释它,那么错误消息将告诉您确切的问题是什么。
,std :: vector与输出
for(const auto& band : bandsVec)
{
std::cout<<band.bandName<<" "<<band.listofMembers<<std::endl;
}
,
您尚未提供将结构序列化到流中的方法。 您必须提供操作员>>。它可以是成员函数,也可以是单独的运算符。很少将其作为成员函数提供,其原因在下面的示例中进行说明。
如果您希望将所有内容保留在班级内,则可以使用friend。从技术上讲,它将是一个单独的运算符,但是您将代码放在类中。
#include <cstring>
#include <iostream>
#include <string>
// member function
class Band1 {
std::string name{"name"};
std::string members{"members"};
public:
// this (pointer to the Band itself) is implicitly passed as the first parameter and the stream is the second
// note the difference with non-member function where the stream is the first and reference to Band is the second parameter
// this results in a very weird call (see example in main)
std::ostream& operator<<(std::ostream& os) {
return os << name << members;
}
};
// operator
struct Band2 {
std::string name{"name"};
std::string members{"members"};
};
std::ostream& operator<<(std::ostream& os,const Band2& band) {
return os << band.name << band.members;
}
// friend operator
class Band3 {
// note the friend operator is in private section,but this is not a member function
friend std::ostream& operator<<(std::ostream& os,const Band3& band) {
return os << band.name << band.members;
}
std::string name{"name"};
std::string members{"members"};
};
int main(int argc,char *argv[])
{
Band1{} << std::cout << std::endl; // very confusing call in case of member function
std::cout << Band2{} << std::endl;
std::cout << Band3{} << std::endl;
return 0;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。