2013-07-25 60 views
0

我有以下類(在C++):使用操作者overloader在操作重載函數

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; 
}; 

然而,它標誌着線產生一個錯誤。 T'm假設它與Card類中的<<超載有關。我究竟做錯了什麼?我該如何解決?

+0

將它定義爲一個自由的功能,這需要'的std :: ostream的&'作爲第一個參數和類作爲第二。 –

回答

0

由於第一個參數是ostream,所以不能將插入作爲成員函數過載到ostream中。你需要使它成爲一個免費的功能:

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

,你超載將有運營商被稱爲:

Card c; 
c << std::cout; 

這是相當unidiomatic。

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

使用此代碼...