Hey Everyone,
I've written this Gambling game in Object-oriented programming. There is a public data member Cash in the class gamble - i want to use it in the main function, how do i do this? (See lines 79, 81 and 84)
Are you sure Cash should be a static member? You're initializing it in the constructor, where you usually want to initialize normal members only. This way every time you construct a Gamble object Cash will be reseted to 100.
Otherwise as far as I can see, you're accessing it correctly.
Well actually, i didn't put that static when i first wrote the code, but then my compiler said
Gamble.cpp: In function ‘int main()’:
Gamble.cpp:13: error: invalid use of non-static data member ‘Gamble::Cash’
Gamble.cpp:79: error: from this location
So I put the static in there, then it gave me another error which reminded me that Static shouldn't go there. you're right it shouldn't be there - i just forget to get rid of it before pasting my code here.
Still, how can i use that member in the main function?
#include <iostream>
#include <cstdlib>
#include <time.h>
usingnamespace std;
class Gamble
{
public:
Gamble();
void getBet(int bet);
void cash();
int slotMachine();
int Cash; // you don't need static here
private:
int Bet;
bool allsame();
bool twosame();
bool insequence();
int ran1, ran2,ran3;
};
Gamble::Gamble()
{
Cash = 100;
}
void Gamble::getBet(int bet)
{
if(bet < Cash){Bet = bet;slotMachine();}
if(bet == 0){cout<<"You leave with $"<<Cash<<"."<<endl; abort();}
if (bet > Cash){cout<<"You do not have that much money!"<<endl;}
}
int Gamble::slotMachine()
{
srand(time(NULL));
ran1 = 1+rand()%5;
ran2 = 1+rand()%5;
ran3 = 1+rand()%5;
cout<<"Slot Machine: "<<ran1<<" "<<ran2<<" "<<ran3<<endl;
if(allsame()){cout<<"ALL THE SAME"<<endl;return (Bet*2);}
if(twosame()){cout<<"TWO THE SAME"<<endl;return (Bet*1);}
if(insequence()){cout<<"THREE IN SEQUENCE"<<endl;return (Bet*3);}
else {return (Bet*-1);}
}
void Gamble::cash()
{
Cash=Cash+slotMachine();
}
bool Gamble::allsame()
{
if(ran1==ran2 && ran2==ran3) returntrue;
elsereturnfalse;
}
bool Gamble::twosame()
{
if(ran1==ran2 || ran2==ran3) returntrue;
elsereturnfalse;
}
bool Gamble::insequence()
{
if(ran3==(ran2+1) && ran2==(ran1+1)) returntrue;
elsereturnfalse;
}
int main()
{
cout<<"GAMBLING GAME"<<endl;
cout<<"Turn the slot machine"<<endl;
cout<<"if two numbers are the same, your money doubles"<<endl;
cout<<"if three numbers are the same, your number triples"<<endl;
cout<<"if the numbers are in a sequence,your money quadruples!"<<endl;
int b;
Gamble Gambler;
while(Gambler.Cash>=0)
{
cout<<"\n\nYou have $"<<Gambler.Cash<<"\nWhat is your bet? $"; cin>>b;
Gambler.getBet(b);
}
if(Gambler.Cash==0)
{
cout<<"You've spent all your money!"<<endl;
}
return 0;
}
You was calling member functions in a wrong way. You have to create an object (you did this with Gamble Gambler;) and call functions from the object.
See http://www.cplusplus.com/doc/tutorial/classes/