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では、カード クラスで使用するために << をオーバーロードしました。

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

2 に答える 2

4

必要な実装は 1 つだけです。ostreamを受け取ってすべての印刷ロジックを実行する Print 関数を作成し、それを呼び出してから呼び出すことができます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;
}
于 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 に答える