Reputation: 11
for homework, I need to write a program in cpp with a class composed of an array of pointer to function and operators. I need to create an operator + so as when in the main, this would happen:
int main()
{
int SIZE = 5;
ptrF* arrPtrF = new ptrF[SIZE];
arrPtrF[0] = add;
arrPtrF[1] = sub;
arrPtrF[2] = mult;
arrPtrF[3] = div1;
arrPtrF[4] = pow;
Delegate D1(arrPtrF, SIZE)
cout<< D1[0](6, 7) + D1[0](1, 2)<<endl;
}
the outcome is 15
I am finding difficulty with writing the operator+ ( which in this case need to take take a object parameter)
at first i tried this:
Delegate Delegate:: operator + (const Delegate& b)
{
Delegate tmp;
tmp.m_ptrF[i] = m_ptrF[i] + b.m_ptrF[i];
return tmp;
}
but it gave me an error about the i and b.m_ptrF->initialized i and something about an enum type.
then i tried this:
int Delegate:: operator + (const Delegate& b)
{
int tmp;
int i, x,y;
tmp = m_ptrF[i](x, y) + b.m_ptrF[i](x, y);
return tmp;
}
but it gives me an error->initialized x,y,i knowing that i is index and x,y the parameters of the pointer to function.
what can i do to make it work?
Upvotes: 0
Views: 76
Reputation: 87959
It looks like D1[0](6, 7)
is supposed to perform 6 + 7
returning an int
and D1[0](1, 2)
is supposed to perform 1 + 2
also returning an int
. So the addition in D1[0](6, 7) + D1[0](1, 2)
is just a regular int
addition.
So in other words you are not supposed to be overloading Delegate::operator+
instead you are supposed to writing something like this
XXX Delegate::operator[](int i) const
{
...
}
where XXX
is a function like type that will perform the addition on the later parameters.
So XXX
will be something like
class XXX
{
public:
int operator()(int x, int y) const
{
...
}
...
};
But XXX
will have to perform addition, or substraction or whatever, as appropriate.
So the expression D1[0](6, 7)
becomes temp(6,7)
where temp is an object of the XXX
type above.
At least that's my best interpretation. It's clear that you have misunderstood your requirements.
Upvotes: 1