我想超载<< 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;
}
}
Run Code Online (Sandbox Code Playgroud)
我声明我ostream& 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";
Run Code Online (Sandbox Code Playgroud)
你的错误很简单.您尝试调用:os << Ex.z,其中z是a Zustand,并且Zustand没有ostream为其实现运算符.您可能希望将其值打印enum为整数.编译器不知道如何打印出来Zustand,所以你必须告诉它如何.