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;
}

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...