C++ moving classes away to separate files
I will use the deck class as an example:
In a file with ".h" extension. typically you name this after the class it contains, but that is just a strong recommendation, not a requirement. This is then #included in your other files where the class is needed. for custom header files, use #include "myfile.h", not #include <myfile>. the quotation marks tell it to look in a directory relative to the file it is being included to instead of the system defined locations.
#ifndef _DECK_H
#define _DECK_H
class deck{
private:
char types[4]={'H','S','D','C'};
char numbers[14]={'1','2','3','4','5','6','7','8','9','0','J','Q','K','A'};
char used_types[50];
char used_numbers[50];
int used_quantity=0;
public:
void give_card(int *ok, int x, char *type,char *number);
}
#endif
And in a .cpp file, define the function bodies. Again, name doesn't actually matter, but it's easier to remember what it is if you use the class name.
void deck::give_card(int *ok, int x, char *type,char *number){
int seed=1;
//if (*ok==0)seed=55;
srand(time(0)/seed); <== remove this. this only needs to be called once EVER
string combine;
char r_type=types[rand()%3];
char r_number=numbers[rand()%14];
for(int i=0;i<used_quantity;i++){
if(r_type==used_types[i] && r_number==used_numbers[i]){*ok=0; break;}
else *ok=1;
}
if(*ok!=0){
used_types[used_quantity]=r_type;
used_numbers[used_quantity]=r_number;
used_quantity++;
type[x]=r_type;
number[x]=r_number;
}
}
Only code things i will note are the re-seeding of the RNG, which is bad, and declaring global variables, which while sometimes necessary is frowned upon. Seed the RNG as one of the first things you do in main(), then just leave it.
Each file (including the .h files) do need to have their own #includes. Similarly, the #ifndef, #define, and #endif in the header file prevent infinite re-inclusion, as things may only be defined once. #pragma once as the first line in any .h file MAY also accomplish this similarly, but it is non-standard and not 100% guaranteed to be supported. That 1% of systems that don't support something will always be the ones you end up having to use...
To compile, just add the extra .cpp files to the command line.
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now