运算符重载<<,打印对象矢量时遇到问题

trouble overloading << operator, trouble printing vectors of objects

本文关键字:lt 遇到 问题 打印 重载 运算符 对象      更新时间:2023-10-16

标题文件:

#ifndef CART_H
#define CART_H
#include "Tops.h"
#include <iostream>
#include <vector>
using namespace std;
class Cart
{
public:
    Cart();
    void addTop(Tops& top);
    friend ostream& operator<<(ostream& ostr, const Cart& c);

private:
    vector<Tops> tops;
};
#endif

实现文件:

#include "Cart.h"
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
Cart::Cart() { }
void Cart::addTop(Tops &top)
{
    tops.push_back(top);
}
ostream& operator<<(ostream &ostr, const Cart &c)
{
    ostr << "TOPS IN CART:n-------------n";
    for (auto const top : c.tops) {ostr << top << endl; } // no match for 'operator<<'
    return ostr;
}

问题:我一直在获得"不适合操作员&lt;&lt;"错误,我不知道为什么,我也不知道这是什么意思。当我搜索此错误时,导致其他人代码中错误的原因不适用于我的。

在您的声明中,您已经说明购物车的参数将是const:

friend ostream& operator<<(ostream& ostr, const Cart& cart);

但是您的定义没有:

ostream& operator<<(ostream &ostr, Cart &c)

他们需要匹配(无论是const还是两者都不 - 两者都在这里)才能有任何用途。