Reputation: 1272
I have the following operator overload code:
public static Set operator+(Set left, Set right)
{
Set sum=new Set(left.Capacity+right.Capacity);
for (left.iterator_init(); !left.iterator_end(); left.iterator_next())
sum.add_member(left.iterator_current());
for (right.iterator_init(); !right.iterator_end(); right.iterator_next())
sum.add_member(right.iterator_current());
return sum;
}
Set is a class with an array of int numbers with Capcity length.
The function add_member inserts a number into the array.
I also have a class OrderedSet that inherits Set like this:
class OrderedSet : Set
In this class I override "add_member" function to insert the numbers ascending. Now I want to use the parent class (Set) operator+ overload the exact same way on OrderedSet, in a way where don't acctually have to rewrite the function again, but depend on the overload from the parent class. So if I wanna change the way I add two Sets or OrderedSets I will have to change the operator code ONLY on Set.
I tried this:
public static OrderedSet operator+(OrderedSet left, OrderedSet right):base(left,right)
{
}
But with no luck, I get syntax error. So, what am I missing?
Upvotes: 1
Views: 440
Reputation: 50114
I think the neatest way to do this is to provide a Set
constructor that creates a set by merging two sets
protected Set(Set left, Set right)
{
this.Capacity = left.Capacity + right.Capacity;
for (left.iterator_init(); !left.iterator_end(); left.iterator_next())
this.add_member(left.iterator_current());
for (right.iterator_init(); !right.iterator_end(); right.iterator_next())
this.add_member(right.iterator_current());
}
which you can reuse in your OrderedSet
class
protected OrderedSet(OrderedSet left, OrderedSet right)
: base(left, right)
{
}
and then reuse both in the add overrides:
public static Set operator +(Set left, Set right)
{
return new Set(left, right);
}
public static OrderedSet operator +(OrderedSet left, OrderedSet right)
{
return new OrderedSet(left, right);
}
That way if the shared "concatenate two sets" logic changes you only have to change it in one place, and if you want OrderedSet
to use its own logic you can stop calling the base
constructor.
Upvotes: 1
Reputation: 5161
You can call the Set version, but since it returns Set you will have to convert your Set to an OrderedSet before you can return.
public static OrderedSet operator+(OrderedSet left, OrderedSet right)
{
Set mySet = (Set)left+(Set)right;
return SoSomethingToConvertYourSetToAnOrderedSet(mySet);
}
Upvotes: 0
Reputation: 19407
The error is generated as the methods for operators are static. It is not possible to use the base keyword in a static method.
As such it's not possible using the :
- It would be possible to call the base class directly within the method body however.
public class Foo
{
public static int Jump(int height)
{
return height * 10;
}
}
public class Bar : Foo
{
public static int Jump(int height)
{
return Foo.Jump(height);
}
}
Upvotes: 2