Rob_Fir
Rob_Fir

Reputation: 165

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

I want to overload << operator. Here is my code:

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

}

I declared my ostream& operator<< as a friend function, definitions inside class and function code seemse to be the same. But I have no idea, why compiler throws me an error "error: no match for ‘operator<<’. Can you help me to figure out where is the problem?

Error message:

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";

Upvotes: 1

Views: 445

Answers (2)

Arnav Borborah
Arnav Borborah

Reputation: 11807

Your error is quite simple. You try to call: os << Ex.z, where z is a Zustand, and that Zustand has no ostream operator implemented for it. You may want to print out the value of that enum as an integer. The compiler doesn't know how to print out a Zustand, so you have to tell it how to.

Upvotes: 6

Daniel Langr
Daniel Langr

Reputation: 23547

Change

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

into

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

and similarly the second line.

Upvotes: 1

Related Questions