EvilZone

Programming and Scripting => C - C++ => : Recon April 11, 2014, 03:16:01 AM

: Need Help with Using Classes in Separate Files
: Recon April 11, 2014, 03:16:01 AM
I have searched Google for half an hour now and can't seem to figure out how to do this properly. I never had any such problems with Java, but C++ seems to be much more complicated. Lend a hand and tell me what I'm doing wrong?

Sandbox.cpp
: (cpp)
/*
    AUTHOR: Recon
    DATE:   9 April 2014
*/

#include <cmath>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <time.h>
#include <cstring>
#include <string>
#include "Die.cpp"

using namespace std;

int randRange(int minimum, int maximum);

int main(int argc, char argv[])
{
    Die myDie;
    cout << myDie.roll();
}

int randRange(int minimum, int maximum) {
    return (rand() % (maximum - minimum)) + minimum;
}

Die.cpp
: (cpp)
/*
    AUTHOR: Recon
    DATE:   9 April 2014
*/

#include <stdlib.h>

using namespace std;

class Die
{
    public:
        Die();
        Die(short faceCount);
        ~Die();
        short roll();
    private:
        short defaultFaceCount = 6;
        short faceCount;
};

Die::Die() {
    faceCount = defaultFaceCount;
}

Die::Die(short faceCount) {
    this->faceCount = faceCount;
}

short Die::roll() {
    return (short) (rand() % faceCount - 1) + 1;
}
: Re: Need Help with Using Classes in Separate Files
: iTpHo3NiX April 11, 2014, 03:30:01 AM
Use the [ code=cpp ] opening bbcode tag to use the syntax highlighter for those with knowledge in c++ to be able to help you out :P
: Re: Need Help with Using Classes in Separate Files
: bluechill April 11, 2014, 05:59:52 AM
Well besides your fucked up main statement:

int main(int argc, char argv[])

should be

int main(int argc, char *argv[])

and missing a destructor which you defined/declare but don't implement (~Die), it compiles fine for me.

:
[11:58 PM Thu Apr 10][0][bluechill /Users/bluechill/test]$ clang++ -stdlib=libc++ -std=c++11 main.cpp -o test
[11:58 PM Thu Apr 10][0][bluechill /Users/bluechill/test]$ ./test
1[11:59 PM Thu Apr 10][0][bluechill /Users/bluechill/test]$

However, you're really supposed to use headers and source files.  Put the implementations of Die in Die.cpp and #include "Die.h" where you define the class (the class Die { ... } portion).  And then in main.cpp #include "Die.h".  When you compile, then you must do the following:

clang++ -stdlib=libc++ -std=c++11 -c Die.cpp -o die.o
clang++ -stdlib=libc++ -std=c++11 -c main.cpp -o main.o
clang++-stdlib=libc++ -std=c++11 -o test main.o die.o
: Re: Need Help with Using Classes in Separate Files
: Stackprotector April 11, 2014, 10:04:53 AM
Try to first do this with normal functions and as bluechill says drop your direct cpp file include and use a header with header guards like

die.h
: (cpp)
#ifndef DIE_HEADER_GUARD
#define DIE_HEADER_GAURD

class Die {
/***/
}

/**/
#endif