在运算符重载函数中使用运算符重载器

Use an operator overloader in an operator overloading function

本文关键字:运算符 重载 函数      更新时间:2023-10-16

我有以下类(在C++中):

class Card
{
public:
    //other functions
    std::ostream& operator<< (std::ostream& os)
    {
        if (rank < 11) os << rank;
        else if (rank == 11) os << "J";
        else if (rank == 12) os << "Q";
        else if (rank == 13) os << "K";
        else os << "A";
        switch (suit)
        {
        case 0:
                os << char (6);
            break;
        case 1:
            os << char (3);
            break;
        case 2:
            os << char (4);
            break;
        case 3:
            os << char (5);
            break;
        }
    }
private:
    Suit suit;
    Rank rank; //these are both pre-defined enums
}

这个类别:

class Hand
{
public:
    std::ostream& operator<< (std::ostream& os)
    {
        for (std::vector<Card>::iterator iter = cards.begin(); iter < cards.end(); ++iter)
            os << *iter << ", "; //THIS LINE PRODUCES THE ERROR
        return os;
    }
private:
    std::vector<Card> cards;
};

但是,它会在标记的线上产生错误。假设它与Card类中的<<重载有关。我做错了什么?我该如何解决这个问题?

不能将插入作为成员函数重载到ostream中,因为第一个参数是ostream。你需要让它成为一个免费的功能:

std::ostream& operator<<(std::ostream&, Card const &);

您过载的操作员必须被称为:

Card c;
c << std::cout;

这是非常独特的。

public:
    Suit suit;
    Rank rank; //these are both pre-defined enums

使用此代码。。。