Creating a Derived Class in C++ -
this question has answer here:
so im trying make die class , loadeddie class die class base , loadeddie class derived. difference between 2 classes roll function in loadeddie has 25% chance of getting highest number, whereas die, has 1/6 chance. 1st time working derived class , seem have quite problem trying complete task. can explain me how works , show me how classes (as im visual learner , need examples). know base class (die) works tested out before moving loadeddie.
die.cpp
#include<iostream> #include <cstdlib> using namespace std; class die{ public: die(); die(int numside); virtual int roll() const; int rolltwodice(die d1, die d2); int side; }; die::die():side(6){} die::die(int numside):side(numside){} int die::roll() const{ return rand() % side + 1; } int die::rolltwodice(die d1, die d2){ return d1.roll()+d2.roll(); }
loadeddie.cpp
#include<iostream> #include <cstdlib> #include "die.cpp" using namespace std; class loadeddie: public die{ public: loadeddie(); loadeddie(int numside); virtual int loadedroll() const; }; loadeddie::loadeddie():side(6){} loadeddie::loadeddie(int numside):side(numside){} int loadeddie::loadedroll() const{ if ((rand() % 2)+1) = 1){ return side; } return (rand() % (side-1)) + 1; } int loadeddie::rolltwodice(loadeddie d1, loadeddie d2){ return d1.roll()+d2.roll(); }
my dietester.cpp (just main class test if above classes work):
#include "loadeddie.cpp" #include<iostream> #include<time.h> #include <stdlib.h> using namespace std; int main(){ srand(time(null)); die d(6); loadeddie dl(6); cout << d.roll()<<endl; cout<<"ld " << dl.roll()<<endl; }
with classes above, error when run dietester.cpp (if helps):
in file included dietester.cpp:1: loadeddie.cpp: in constructor ‘loadeddie::loadeddie()’: loadeddie.cpp:13: error: class ‘loadeddie’ not have field named ‘side’ loadeddie.cpp: in constructor ‘loadeddie::loadeddie(int)’: loadeddie.cpp:15: error: class ‘loadeddie’ not have field named ‘side’ loadeddie.cpp: in member function ‘virtual int loadeddie::loadedroll() const’: loadeddie.cpp:18: error: expected primary-expression before ‘=’ token loadeddie.cpp:18: error: expected ‘;’ before ‘)’ token
i believe these errors due me not deriving classes properly. can explain me how done?
it's bad form #include cpp files. if want it, rid of #include "die.cpp" statement in main.cpp. it's included in loadeddie.cpp , including twice , defining twice--hence 'redefinition' error.
Comments
Post a Comment