0

我已经成功地重载了 '<<' 运算符,我认为它被称为插入运算符。我有一个打印卡片对象实例信息的打印函数,使用运算符时如何调用此打印函数

例子:

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

2 回答 2

4

您只需要一种实现。您可以创建一个 Print 函数,该函数接受ostream并执行所有打印逻辑,然后从Print()and调用它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;
}
于 2013-02-13T20:06:33.247 回答
0

你需要aCard.Print()operator<<Print()

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

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

于 2013-02-13T20:07:20.323 回答