Re: abstract class question about operators
- From: "Ben Voigt [C++ MVP]" <rbv@xxxxxxxxxxxxx>
- Date: Tue, 26 Jun 2007 13:02:04 -0500
"t f" <thetoefungus@xxxxxxxxx> wrote in message
news:e6CfBZBuHHA.1164@xxxxxxxxxxxxxxxxxxxxxxx
hi
just a quick question - i have the something like the following
public abstract class ClassA
{
protected int iA;
public int Value { get {return iA;} set { iA = value;}}
public ClassA(int value)
{ iA = value; }
public static ClassA operator +(ClassA a1, ClassA a2)
{
a1.Value = a1.Value + a2.Value;
return a1;
}
public static ClassA operator -(ClassA a1, ClassA a2)
{
a1.Value = a1.Value - a2.Value;
return a1;
}
}
public class ClassB : ClassA
{
public ClassB(int value) : base(value)
{ }
}
public class ClassC : ClassA
{
public ClassB(int value) : base(value)
{ }
}
Problem is, if i try this
ClassB cb1 = new ClassB(1);
ClassB cb2 = new ClassB(2);
ClassB cb3 = cb1 + cb2;
I get an error as cb1 + cb2 is of type ClassA....
Question: Is there a way of putting all my operator overloads in the base
class and instead of having to put them in each of the derived classes?
You've already done so. You've also discovered the limitations, which have
to do with covariance.
This method could certainly work for
static bool operator!=(ClassA a1, ClassA a2);
and similar, but the return type must be fixed and doesn't vary with the
derived type.
Thanks
t f
.
- References:
- abstract class question about operators
- From: t f
- abstract class question about operators
- Prev by Date: Re: When is "volatile" used instead of "lock" ?
- Next by Date: Re: UPS Web Service
- Previous by thread: Re: abstract class question about operators
- Next by thread: Re: .NET security exception
- Index(es):
Relevant Pages
|