0

我有以下课程(在 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。我究竟做错了什么?我该如何解决?

4

2 回答 2

0

您不能将插入ostream作为成员函数重载到 a 中,因为第一个参数是ostream. 您需要使其成为免费功能:

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

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

Card c;
c << std::cout;

这是很不习惯的。

于 2013-07-25T16:56:49.003 回答
0
public:
    Suit suit;
    Rank rank; //these are both pre-defined enums

使用此代码...

于 2013-07-30T10:39:42.323 回答