【问题标题】:trouble overloading << operator, trouble printing vectors of objects重载 << 运算符的麻烦,打印对象向量的麻烦
【发布时间】:2017-12-02 06:48:29
【问题描述】:

头文件:

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

问题:我不断收到“不匹配运算符

【问题讨论】:

  • 缺少const。您需要在实现中使用ostream&amp; operator&lt;&lt;(ostream &amp;ostr, const Cart &amp;c) 来匹配friend 声明的原型。
  • 还有几个其他错误(itt*) -> (*itt),尽管您应该只使用 foreach 循环:for (auto top : c.tops) { ostr &lt;&lt; top &lt;&lt; endl; }
  • 通过在实现中省略const,该实现与您的预期完全不同。它是有效的,但它不是相同的功能。这就是您没有收到编译器错误的原因。
  • 注意:要利用 @Justin 的建议,请确保您的编译器启用了 C++11 或更新的标准。
  • @EmilyLerman “你可以在一个项目中多次重载同一个操作符吗?” 这不依赖于项目,而是依赖于函数签名:std::ostream&amp; operator&lt;&lt;(std::ostream&amp;, const TypeA&amp;)std::ostream&amp; operator&lt;&lt;(std::ostream&amp;, const TypeB&amp;) 的不同足以让编译器解析 "competing" 函数重载定义。

标签: c++ vector overloading codeblocks


【解决方案1】:

在您的声明中,您已声明 Cart 参数将为 const:

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

但你的定义没有:

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

他们需要匹配(要么都是 const 要么都不 - 两个 const 都在这里)才能使朋友声明有任何用处。

【讨论】:

  • 这里有很多相互竞争的错误。这只是一个。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-11
相关资源
最近更新 更多