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