Hi again and thanks in advance !Any help would be very appreciated cause i'm having a test tomorrow and i need some help!
So i wanna have a class called Bag and a subclass Set.In bag we have 2 constructors,
an insert function , getsize function , getsum (which adds all elements of the bag) , and contains which finds if an element is in the bag or not.
In the subclass is only given that a set cannot have twice the same element
i've made 2 classes but i don't know if they are correct.
And finally i have to overload .If a,b are objects from set then i must have the ability to add
a=b+7;
The theme is i'm having logic error probably cause i'm not getting compile errors but the program once it opens it closes
1.
bag.h
2.
3.
4.
5.
#ifndef BAG_H
6.
#define BAG_H
7.
8.
9.
class Bag
10.
{
11.
protected : int size;
12.
int pos;
13.
int *data;
14.
public:
15.
16.
Bag();
17.
Bag(int k);
18.
~Bag();
19.
int insert(int k);
20.
int getSize();
21.
int getSum();
22.
int contains(int k);
23.
24.
};
25.
26.
#endif
27.
28.
bag.cpp
29.
30.
31.
32.
#include "bag.h"
33.
34.
35.
Bag::Bag()
36.
{
37.
size=1;
38.
data=new int;
39.
}
40.
41.
Bag::Bag(int k)
42.
{
43.
size=k;
44.
data=new int[size];
45.
}
46.
47.
48.
Bag::~Bag()
49.
{
50.
delete [] data;
51.
}
52.
53.
int Bag::insert(int k)
54.
{
55.
if(pos==size)
56.
return 1;
57.
58.
data[pos]=k;
59.
pos++;
60.
return 0;
61.
}
62.
63.
int Bag::getSize()
64.
{
65.
return size;
66.
}
67.
68.
int Bag::getSum()
69.
{
70.
int sum=0;
71.
for(int i=0;i<pos;i++)
72.
sum+=data[i];
73.
return sum;
74.
}
75.
76.
int Bag::contains(int k)
77.
{
78.
for(int i=0;i<pos;i++)
79.
if(data[i]==k)
80.
return 1;
81.
82.
return 0;
83.
}
84.
85.
86.
87.
set.h
88.
89.
90.
91.
#ifndef SET_H
92.
#define SET_H
93.
94.
#include "bag.h"
95.
96.
97.
class Set : public Bag
98.
{
99.
public:
100.
101.
Set();
102.
103.
Set(int k);
104.
bool push(int k);
105.
Set operator+(int k);
106.
Set operator+(Set a);
107.
};
108.
109.
#endif
110.
111.
112.
113.
114.
#include "set.h"
115.
#include "bag.h"
116.
117.
Set::Set() : Bag()
118.
{
119.
120.
}
121.
122.
123.
Set::Set(int k) : Bag(k)
124.
{
125.
126.
}
127.
128.
bool Set::push(int k)
129.
{
130.
if(contains(k))
131.
return false;
132.
133.
else
134.
insert(k);
135.
}
136.
137.
Set Set::operator+(int k)
138.
{
139.
Set newset;
140.
141.
if(pos==size)
142.
return *this;
143.
144.
newset=*this;
145.
146.
if(contains(k)==false)
147.
{
148.
newset.data[pos]=k;
149.
newset.pos++;
150.
}
151.
return newset;
152.
}
153.
Set Set::operator+(Set a)
154.
{
155.
Set newset;
156.
157.
158.
159.
for(int i=0;i<a.pos;i++)
160.
newset=newset+a.data[i];
161.
162.
return newset;
163.
}
164.
165.
166.
main.cpp
167.
168.
#include <cstdlib>
169.
#include <iostream>
170.
#include "bag.h"
171.
#include "set.h"
172.
173.
using namespace std;
174.
175.
int main(int argc, char *argv[])
176.
{
177.
Set a;
178.
Set b(5);
179.
180.
a=b+7;
181.
182.
183.
184.
system("PAUSE");
185.
return EXIT_SUCCESS;
186.
}