2013-02-13 46 views
0

我已經成功地重載了'< <'運算符,我相信它被稱爲插入運算符。我有打印卡對象的實例的信息打印功能,我怎麼能調用這個打印功能,使用操作時使用print函數輸出重載的<<運算符?

例如:

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 
} 

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

回答

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

您需要從兩個版本中返回'ostream'。 – juanchopanza 2013-02-13 20:21:46

0

您在operator<<Print()

需要

你不說錯誤是什麼,但基本上你打電話給一個全局定義的Print()函數或函數,它不代表你的代碼存在。

+0

那麼我收到一個錯誤,說我的Print函數沒有在這個範圍中定義,但是當我使用'aCard.Print()'時,我收到另一個錯誤,指出:錯誤'const Card'作爲'void' :: Print'丟棄限定符[-fpermisssive] – John 2013-02-13 21:48:47

+0

@JohnDream對。這很容易實際解決 - 只需在定義的類聲明和void Card :: Print()const {...}中聲明Print()'const',即'void Print()const;'' – 2013-02-13 23:08:55