我已经成功地重载了 '<<' 运算符,我认为它被称为插入运算符。我有一个打印卡片对象实例信息的打印函数,使用运算符时如何调用此打印函数
例子:
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
中,我重载了 << 以与我的卡类一起使用。
卡片.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
}
卡片.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&)
};