我正在尝试重载,operator<<
但我一直将地址作为输出。
例如一个Card *c = new Card(5,3);
那么如果我尝试用我的超载输出卡片operator<<
,
地址输出而不是说'5 of Clubs'
cout << c; //0x100100ff0 ?????????????
//Card.h
#ifndef JS_CARD_H
#define JS_CARD_H
#include <ostream>
using std::ostream;
#include <string>
using std::string;
#include <vector>
using std::vector;
namespace JS {
class Card {
friend ostream &operator<<(ostream &out, const Card &rhs);
public:
enum Suit { DIAMONDS, HEARTS, SPADES, CLUBS };
enum Rank { ACE = 1, JACK = 11, QUEEN = 12, KING = 13 };
Card(int rank, int suit) : rank(rank), suit(suit){}
string getRank() const;
string getSuit() const;
int getRankValue() const;
int operator+(const Card& rhs);
void displayCard(const Card &rhs);
private:
int rank;
int suit;
};
}
#endif
//Card.cpp
ostream
&operator<<(ostream &out, const Card &rhs) {
out << rhs.getRank() << " o f" << rhs.getSuit();
return out;
}
string
Card::getSuit() const {
switch (suit) {
case SPADES: return "Spades"; break;
case HEARTS: return "Hearts"; break;
case DIAMONDS: return "Diamonds"; break;
case CLUBS: return "Clubs"; break;
default: return ""; break;
}
}
string
Card::getRank() const {
switch (rank) {
case ACE: return "Ace"; break;
case JACK: return "Jack"; break;
case QUEEN: return "Queen"; break;
case KING: return "King"; break;
default:
stringstream out;
out << rank;
return out.str();
break;
}
}
//main.cpp
#include "Deck.h"
#include "Card.h"
#include <iostream>
using std::cout;
using namespace JS;
int main(int argc, const char * argv[]) {
Card *c = new Card(5,3);
Card *c1 = new Card(1,1);
cout << c; //0x100100ff0 ?????????????
cout << '\n'; //5 of Clubs
c->displayCard();
return 0;
}