I tried to implement the + part while overloading the operator, but it didn't work I generally hit it to check, but it didn't work, so I'm leaving a message. I think it's a grammar problem, but I don't know because it's my first C++. Please look at the + operator and explain why you got the + part wrong.
#include <iostream>
using namespace std;
class IntegerSet {
int numElements, maxNumElements;
int *elements;
public:
IntegerSet(int max) {
numElements = 0;
maxNumElements = max;
elements = new int[max];
}
~IntegerSet(); // to implement
int addAnElement(int element); // add an integer element, to implement
IntegerSet operator+(const IntegerSet& other); // union, to implement
IntegerSet operator-(const IntegerSet& other); // difference, to implement
IntegerSet operator*(const IntegerSet& other); // intersection, to implement
friend ostream& operator<<(ostream& os, const IntegerSet& integerSet);
};
IntegerSet::~IntegerSet() {
delete(elements);
}
int IntegerSet::addAnElement(int element) {
if (numElements < maxNumElements) {
elements[numElements] = element;
numElements++;
return 0;
}
else
return -1;
}
Why not here?
IntegerSet IntegerSet::operator+(const IntegerSet& other) {
IntegerSet temp(5);
temp.addAnElement(22);
return temp;
}
ostream& operator<<(ostream& os, const IntegerSet& integerSet) {
cout << "number of elements : " << integerSet.numElements << "\n";
for (int i = 0;i<integerSet.numElements;i++)
cout << integerSet.elements[i]<<" ";
cout << "\n";
return os;
}
int main() {
IntegerSet a(10), b(5);
int i;
for (i = 0;i < 5;i++) {
a.addAnElement(i);
b.addAnElement(10 - i);
}
cout << a << endl;
cout << b << endl;
IntegerSet c = a + b;
return 0;
}
If you've had problems with grammar, it's normal that you can't compile.
Why don't we take a look at the logic of the function?
The operator+ you posted in the question has no problem with the program code.
I don't think it's the code you've actually tried. I think it would be better to look at the escape conditions of the loop from your original logic.
And just to be precise, I think we need to define a copy generator to work.
The default copy constructors are:
The copy constructor calls at the following points:
© 2024 OneMinuteCode. All rights reserved.