簡體   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