c++ - overloaded operator<< outputs an address instead of data members -
i'm trying overload operator<<
keep getting address output.
for example card *c = new card(5,3);
then if try output card overloaded operator<<
,
the address outputs instead of '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; }
c
not card object. pointer card object. if want use operator it, need dereference it, this:
cout << *c;
but then, why c
pointer anyway? if want card object, make one. there no reason dynamic allocation here.
card c(5, 3); cout << c;
your code has memory leak anyway. every new
, need delete
. stop using new
, , don't need delete
.
Comments
Post a Comment