繁体   English   中英

错误:C ++中由ostream定义的'operator <<'不匹配

[英]error: no match for ‘operator<<’ defining by ostream in c++

我想重载<< 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";

您的错误非常简单。 您尝试调用: os << Ex.z ,其中zZustand ,并且该Zustand没有Zustand实现的ostream运算符。 您可能需要将该enum的值打印为整数。 编译器不知道如何打印Zustand ,因此您必须告诉它如何进行。

更改

os << "Auflage:" << Ex.aufl_num <<","<< "Zustand:"<<Ex.z<<","<<"verliehen";

进入

os << "Auflage:" << Ex.aufl_num <<","<< "Zustand:"
   << static_cast<std::underlying_type<Zustand>::type>(Ex.z) 
   <<","<<"verliehen";

和第二行类似。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM