我已經成功地重載了'< <'運算符,我相信它被稱爲插入運算符。我有打印卡對象的實例的信息打印功能,我怎麼能調用這個打印功能,使用操作時使用print函數輸出重載的<<運算符?
例如:
Card aCard("Spades",8); //generates an 8 of spades card object
aCard.Print(); // prints the suit and value of card
cout << aCard << endl; // will print something successfully but how can I get the same results as if I were to call the print function?
我在執行文件card.cpp
我已經超載用於我的卡類的< <。
Card.cpp
void Card::Print()
{
std::cout << "Suit: "<< Suit << std::endl;
std::cout << "Value:" << Value << std::endl;
}
std::ostream& operator<<(std::ostream &out, const Card &aCard)
{
Print();//this causes an error in the program
}
Card.h
class Card
{
public:
std::string Suit;
int Value;
Card(){};
Card(std::string S, int V){Suit=S; Value=V};
void Print();
friend std::ostream& operator<<(std::ostream&, const Card&)
};
您需要從兩個版本中返回'ostream'。 – juanchopanza 2013-02-13 20:21:46