Overloading Operators

I'm trying to make a dice class and I want to have a way to do something like
1
2
3
Dice d6();
int x;
x = 2 ~ d6();

where ~ takes the 2 and says "Oh! Roll the d6 twice and add the results together!" or something like that.

Right now I just can't seem to get the base overloading to work (I'm not even sure if what I wanna do can work).

Is there anyway to do this?
What would actually be the best, though, is if there is a way to just say 2d6 instead of 2~d6. But I really don't think that's possible. Although I'd be happy to be wrong. :D
I'm about to leave so here's my code so far.

main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include "dice.h"

#include <cmath>
#include <fstream>
#include <iostream>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <time.h>
using namespace std;

int main()
{
	srand(time(NULL));
	Dice three_d6(6,3);
	Dice d6(6);
	int x = 2 ~ d6;

	cout << three_d6.roll() << endl;
	cout << d6.roll() << endl;
	cout << x << endl;
}


dice.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#ifndef DICE_H_
#define DICE_H_

class Dice
{
	int type;
	int amount;

public:
	Dice(int x);
	Dice(int x, int y);
	const int operator~();
	int roll();
};

#endif /* DICE_H_ */ 


dice.cpp
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
#include "dice.h"

#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
using namespace std;

Dice::Dice(int x)
{
	type = x;
	amount = 1;
}

Dice::Dice(int x, int y)
{
	type = x;
	amount = y;
}

const int operator~(Dice ds)
{
	return 1;
}

int Dice::roll()
{
	srand(time(NULL));
	int x = 0;

	for(int i=1;i<=amount;i++)
		x += (rand() % type + 1);

	return x;
}
Last edited on
Topic archived. No new replies allowed.