簡體   English   中英

正確重載 << 運算符

[英]Properly overload << operator

我對 c++ 很陌生,我目前的問題是output使用重載運算符的結構。 我已經盡力了,但顯然還不夠。 任何人都知道為什么我的編譯器不斷推出這個錯誤:\main.cpp|16|error: no match for 'operator<<' (operand types are 'std::basic_ostream' and 'const Eyecolor')|

這是對應的代碼:

#include <iostream>
#include <string>
using namespace std;

enum class Eyecolor {blue, brown, green};

struct PStruct {
    string surname;
    Eyecolor eyecolor;
    double height;
    bool gender;
    friend std::ostream& operator<<(std::ostream& os, const PStruct& ps);
};
std::ostream& operator<<(std::ostream& os, const PStruct& ps)
{
    os << ps.surname << '/' << ps.height << '/' << ps.gender << '/' << ps.eyecolor; //line 16
    return os;
}
void print(){
    cout << os;
}

int main()
{
    return 0;
}

我很確定我在此之前定義了 operator<< 一行。

無論如何感謝您提前回答

錯誤消息的精簡版本:

no match for 'operator<<' (operand types are 'std::ostream' and 'const Eyecolor')
                                          ----------------------------> ^^ 

該錯誤抱怨缺少operator<<對於Eyecolor 您定義的是PStruct並嘗試在此處調用缺少的運算符:

os << ps.surname << '/' << ps.height << '/' << ps.gender << '/' << ps.eyecolor;
                                          --------------------> ^^

與您為EyeColor PStruct一個。

Enum to string conversion is a long standing annoyance in C++, you can see how much work one has to put into it to get a generic solution here: enum to string in modern C++11 / C++14 / C++17 and future C++20 . 在這里我不打算討論,而只是展示如何讓operator<<工作。

真的沒有冒犯,但讓操作員成為朋友聞起來像Cargo Cult Programming 您可能已經在示例中看到了這一點,並且通常需要與操作員交朋友,但在您的代碼中沒有理由這樣做。 此外print()有錯誤。

固定版本可能如下所示:

#include <iostream>
#include <string>

enum class Eyecolor {blue, brown, green};

struct PStruct {
    std::string surname;
    Eyecolor eyecolor;
    double height;
    bool gender;
};
std::ostream& operator<<(std::ostream& os, const Eyecolor ec){
    switch(ec){
        case Eyecolor::blue :
            os << "blue";
            break;
        case Eyecolor::brown :
            os << "brown";
            break;
        case Eyecolor::green :
            os << "green";
            break;
        default:
            os << "unknown color";
    }
    return os;
}

std::ostream& operator<<(std::ostream& os, const PStruct& ps)
{
    os << ps.surname << '/' << ps.height << '/' << ps.gender << '/' << ps.eyecolor;
    return os;
}
void print(const PStruct& ps){
    std::cout << ps;
}

PS: 為什么是“使用命名空間標准;” 被認為是不好的做法?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM