C++ ostream 运算符<<重载



我有一张带有参数(颜色、值)和输出卡参数的方法的卡片。

错误二进制"<<":未找到采用类型为"CardColor"和"CardValue"的右侧操作数的运算符(或者没有可接受的转换)

卡.h

struct Card{
    Color CardColor;
    Value CardValue;
    Card(Color color, Value cardValue) {
        this->CardColor = color;
        this->CardValue = cardValue;
    }
    public:
    friend std::ostream &operator<<(std::ostream &output, const Card c);
};

值.h

#ifndef VALUE_H
#define VALUE_H
enum class Value{ SEDMA, OSMA, DEVITKA, DESITKA, SPODEK, KRAL, ESO, SVRSEK };
#endif

颜色.h

#ifndef COLOR_H
#define COLOR_H
enum class Color { ZALUD, LISTY, SRDCE, KULE };
#endif

主.cpp

#include <Card.h>
std::ostream &operator<<(std::ostream &output, const Card c)
{
    output << c.CardColor << c.CardValue << std::endl;
    return output;
}
void outputCard(Card c)
{
    std::cout << c << std::endl;
}

来自您的评论:

二进制"<<":未找到采用类型为"CardColor"和"CardValue"的右侧操作数的运算符(或者没有可接受的转换)

还需要为"颜色"和"值"类提供operator<<

Color 类的示例:

#ifndef COLOR_H
#define COLOR_H
#include <iostream>
enum class Color { ZALUD, LISTY, SRDCE, KULE };
inline std::ostream& operator<<(std::ostream& os, const Color& col)
{
    switch (col) {
      case ZALUD :
        os << "ZALUD";
        break;
      // ...
    }
    return os;
}
#endif

最新更新