运算符重载<<,打印对象矢量时遇到问题
trouble overloading << operator, trouble printing vectors of objects
标题文件:
#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还是两者都不 - 两者都在这里)才能有任何用途。
相关文章:
- 编译包含字符串的代码时遇到问题
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 呼叫运营商<<临时
- 遇到新行时,有没有办法停止istream_iterator
- 如何防止clang格式在流运算符调用之间添加换行符<<
- <<操作员在下面的行中工作
- 在使用GPU支持编译Tensorflow时,会遇到CUDA_TOOLKIT_PATH未绑定变量
- 如何在C++向量中奇数元素前面加上值-1,我在使用insert函数时遇到了问题
- 在 for 循环中查找问题时遇到困难
- 创建结构的数组时遇到分段错误
- 代码在我的计算机上运行良好,但是在将其提交给coursera时遇到未知的信号11问题
- 为什么我遇到分段错误?
- 在顶点着色器中使用 OpenGl 的未声明标识符,我在顶点着色器中绘制三角形时遇到问题
- 这些是什么样的错误?即使我不在 Linux 上工作,我也遇到了 Linux 错误
- 为什么我在尝试模板时遇到视觉工作室C++错误
- 如何从文本文件中读取数值,直到遇到字符类型?
- 从其他类访问类时遇到问题
- 我已经阅读了很多关于 2d 数组的信息,但我在作业中使用它时遇到了麻烦
- 打印问题.我在数组中打印值时遇到一些问题
- 使用静态成员声明类时遇到问题