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

时间:2013-07-25 16:53:40

标签: c++ operator-overloading

我有以下课程(用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重载有关。我究竟做错了什么?我该如何解决这个问题?

2 个答案:

答案 0 :(得分:0)

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

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

您重载的运算符必须被称为:

Card c;
c << std::cout;

这非常不合时宜。

答案 1 :(得分:0)

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

使用此代码...