使用print函数输出重载<<运营商?

时间:2013-02-13 19:57:51

标签: c++ function

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

示例:

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中,我重载了&lt;&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
}

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

2 个答案:

答案 0 :(得分:4)

您只想要一个实现。您可以制作一个需要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<<包含打印逻辑并从operator<<致电Print

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

答案 1 :(得分:0)

aCard.Print()而非operator<<

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

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