如何通过重载<<运算符来打印矢量中的对象?

How do I print out objects in a vector by overloading the << operator?

本文关键字:lt 对象 何通过 重载 运算符 打印      更新时间:2023-10-16

好吧,所以我对所有这些运算符重载的东西感到困惑,语法对我来说很奇怪,而且我在编程方面也不太擅长。因此,环顾互联网,我显然认为我使用cout <<打印对象的唯一方法是重载它。所以我有一个对象向量,通常如果我只有一个int或字符串的正则向量,那么我只需要使用迭代器,遍历每一个,然后解引用它来打印其中的内容,但我认为这种技术对物体不起作用://以下是我迄今为止所掌握的。。。帮助

BarOne.h   //my header file
#include <string>
#include <vector>
using namespace std;
class BarOne
{
private:
    string name;
    string type;
    string size;
    vector<BarOne> bar;   //vector of BarOne objects
    vector<BarOne>::iterator it;  //iterator for bar
public:
    BarOne();    //constructor
    void addBottle(string, string, string);  //adds a new bottle to bar
    void revealSpace();
    void printInventory();
    friend ostream& operator<<(ostream& os, const BarOne& b);
};

我的实现看起来像:

BarOne.cpp    //implementation
#include "BarOne.h"
#include <iostream>
#include <string>
using namespace std;

BarOne::BarOne()
{
    //adding 4 default bottles
}

void BarOne::addBottle(string bottleName, string bottleType, string bottleSize)
{
    name = bottleName;
    type = bottleType;
    size = bottleSize;
}

void BarOne::printInventory()
{
    for (it = bar.begin(); it != bar.end(); ++it)
    {
        cout << *it << endl;
    }
}

ostream& operator<<(ostream& os, const BarOne& b)
{
    os << b.name << "ttt" << b.type << "ttt" << b.size;
    return os;
}

那么,当我在主目录中调用printInventory时,它为什么什么都不做呢?我超载做错了吗?语法错误?

好的,这也是主要的:

#include "BarOne.h"
#include <iostream>
#include <string>
using namespace std;


int main()
{
    string Tiqo, Peruvian, Wellington, Smooze;
    string vodka;
    string rum;
    string whiskey;
    string small;
    string medium;
    string large;
    //default bottles
    vector<BarOne> bar;   //vector of BarOne objects
    vector<BarOne>::iterator it;  //iterator for bar
    BarOne Inventory;   //BarOne object
    Inventory.addBottle(Tiqo, vodka, large);
    bar.push_back(Inventory);
    Inventory.addBottle(Peruvian, rum, medium);
    bar.push_back(Inventory);
    Inventory.addBottle(Wellington, vodka, large);
    bar.push_back(Inventory);
    Inventory.addBottle(Smooze, whiskey, small);
    bar.push_back(Inventory);

^^^这只是其中的一部分……剩下的只是格式化程序运行时的显示方式。所以好吧,我会试着像别人建议的那样把课程分开。AddBottle将该对象的信息添加到向量中,对吗?它获取信息,然后将其添加到变量名称、类型和大小中,然后放入向量"栏"中。还是没有?

您没有向我们展示您的main()程序。这段代码,再加上你的类设计混淆了条形图的内容,导致了你看到的行为。

operator <<实际上可以输出瓶子的数据。但我确信它被调用的BarOne有一个空的bar向量。您的addBottle()不会在任何位置添加任何内容(特别是不会添加到包含的bar中)。相反,它只是简单地设置外部BarOne对象的属性(数据成员)。

这种混乱的根源是你的课堂设计,BarOne显然是用来充当瓶子和酒吧(里面有瓶子)的。

我建议您重新启动并尝试使用单独的BarBottle类。

BTW:将本地循环中使用的迭代器保留为类成员不是一个好主意。这种方法迟早会遇到可重入性问题。循环迭代器应该是局部变量,最好作用域为循环。