使用打印功能输出过载<<运算符?

Use print function for output of overloaded << operator?

本文关键字:lt 运算符 打印 功能 输出      更新时间:2023-10-16

我已成功重载'<lt;'运算符,我认为它被称为插入运算符。我有一个打印功能,可以打印卡对象实例的信息,当操作员使用时,我如何调用这个打印功能

示例:

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?

在我的实现文件CCD_ 1中,我已经重载了<lt;用于我的卡片类。

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
}

卡片.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&)
};

您只需要一个实现。您可以创建一个Print函数,该函数接受ostream并执行所有打印逻辑,然后从Print()operator<< 调用它

void Card::Print()
{
    Print(std::cout);
}
std::ostream& operator<<(std::ostream &out, const Card &aCard)
{
    Print(out);
}
void Card::Print(std::ostream &out)
{
    out << "Suit: "<< Suit << std::endl;
    out << "Value:" << Value << std::endl;
    return out;
}

或者您可以让operator<<包含打印逻辑,并从Print:调用operator<<

void Card::Print()
{
    std::cout << *this;
}
std::ostream& operator<<(std::ostream &out, const Card &aCard)
{
     out << "Suit: "<< Suit << std::endl;
     out << "Value:" << Value << std::endl;
     return out;
}

您需要operator<<中的aCard.Print(),而不是card.cpp0

std::ostream& operator<<(std::ostream &out, const Card &aCard)
{
    aCard.Print();
}

您没有说明错误是什么,但基本上您调用的是一个全局定义的Print()函数或一个当前代码中不存在的函数。