x.standard[0]
is an object of type
Card
; it is the first
Card
object in the big array of cards in the
Game
object named
x
.
So you're passing an object of type
Card
to the operator
<<
.
C++, of course, has never heard of a
Card
object. Doesn't know what it is. Doesn't know what to do with it. Nobody has ever written the operator:
ostream& operator<<(ostream& os, const Card& cardObject)
which is the operator you're trying to call here.
So, in order to call that operator, you have to write it yourself.
This ought to do it:
1 2 3 4 5 6 7
|
ostream& operator<<(ostream& os, const Card& cardObject)
{
os << "Value: ";
os << cardObject.value;
os << '\n';
return os;
}
|
Like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
|
// Example program
#include <iostream>
#include <string>
using namespace std;
enum struct Suit{Hearts=0, Clubs, Diamonds, Spades};
enum struct Face{Ace=0,Two, Three, Four, Five, Six, Seven,
Eight, Nine, Ten, Jack, Queen, King};
// ==============================
struct Card{
public:
Face face;
Suit suit;
int value;};
ostream& operator<<(ostream& os, const Card& cardObject)
{
os << "Value: ";
os << cardObject.value;
os << '\n';
return os;
}
// =======================================
class Game{
private:
Card standard[52];
public:
void CreateDeck(Game x);
void DealCards();};
// ========================================
int main(){
Game BlackJack;
BlackJack.CreateDeck(BlackJack);
return 0;}
// ~~~~~~~~~~~~~~ Function Line ~~~~~~~~~~~~~~~~
void Game::CreateDeck(Game x){ // only partially completed
for (int i=0;i<13;i++){
x.standard[i].face=Face(i);}
cout<<x.standard[0];
}
|
In this new code, the operator you're trying to call IS now defined. You can see that all it does at the moment is call
<<
again on the stream, with the
int Value
. C++ does already know what to do with an int being used like that (i.e. somewhere, someone else already wrote the operator
ostream& operator<<(ostream& os, const int& someIntValue)
for you.
I just output one of the Card object's variables. If you want Face and Suit as well you'll need to write that code. Of course, there is no operator
ostream& operator<<(ostream& os, const Face& someFaceValue)
; you will have to think about what code to write. Could be something
like this:
1 2
|
if (suit == Hearts) { os << "Hearts";}
etc.
|
You will note that this operator is making use of your struct's public variable. If your struct had private variables that you wanted to use like this, you would need to tell C++ that this operator was a friend of your struct, because a friend is allowed to see the private variables.
There is an example of that here:
https://msdn.microsoft.com/en-us/library/1z2f6c2k.aspx