【发布时间】:2018-02-05 11:33:34
【问题描述】:
我想重载<< operator。这是我的代码:
#include <iostream>
#include <vector>
#include <string>
#include <stdexcept>
#include <algorithm>
#include <cmath>
#include <list>
using namespace std;
enum class Zustand{Neuwertig,Gut,Abgegriffen,Unbrauchbar};
class Exemplar{
private:
int aufl_num;
Zustand z;
bool verliehen;
public:
Exemplar(int aufl_num);
Exemplar(int aufl_num,Zustand z);
bool verfuegbar() const;
bool entleihen();
void retournieren(Zustand zust);
friend ostream& operator<<(ostream& os, const Exemplar& Ex);
};
//Constructor 1;
Exemplar::Exemplar(int aufl_num):
aufl_num{aufl_num},
z{Zustand::Neuwertig},
verliehen{false}
{
if(aufl_num >1000 || aufl_num <1) throw runtime_error("Enter correct number betwee 1 and 1000");
}
// Constructor 2;
Exemplar::Exemplar(int aufl_num,Zustand z):
aufl_num{aufl_num},
z{z},
verliehen{false}
{
if(aufl_num >1000 || aufl_num <1) throw runtime_error("Enter correct number betwee 1 and 1000");
}
ostream& operator<<(ostream& os, const Exemplar& Ex){
if(Ex.verliehen == true){
os << "Auflage:" << Ex.aufl_num <<","<< "Zustand:"<<Ex.z<<","<<"verliehen";
}else{
os << "Auflage:" << Ex.aufl_num <<","<< "Zustand:"<<Ex.z;
}
}
我将ostream& operator<< 声明为友元函数,类和函数代码中的定义似乎相同。但我不知道,为什么编译器会抛出一个错误“错误:'operator
错误信息:
main.cpp: In function ‘std::ostream& operator<<(std::ostream&, const Exemplar&)’:
main.cpp:72:53: error: no match for ‘operator<<’ (operand types are ‘std::basic_ostream<char>’ and ‘const Zustand’)
os << "Auflage:" << Ex.aufl_num <<","<< "Zustand:"<<Ex.z<<","<<"verliehen";
【问题讨论】:
-
请包含完整的错误信息,它会说明编译器试图用什么类型调用
operator<<。 -
minimal reproducible example,拜托。您显示的代码甚至没有尝试调用
operator<<。除此之外,请尝试删除不相关的细节(但保持代码可编译,只是您询问的错误)。 -
我猜编译器在抱怨
Zustand类型缺少operator <<。 -
仔细查看您的错误信息。问题不在于您的
Exemplar类的<<重载,而是没有为您的枚举类定义<<重载。 -
你不会错误地抱怨输出
Ex.z,这是一个enum class吗?见stackoverflow.com/questions/11421432/…
标签: c++