Hello,
I have the following C++-Code:
Definition:
class Klasse
{
public:
Klasse operator+(Klasse Op);
public:
int X;
};
Implementation:
Klasse Klasse::operator+(Klasse Op)
{
Klasse Result;
Result.X = this->X + Op.X;
return Result;
};
I want to transfer it to C#, like this:
class Klasse
{
public int X;
public static Klasse operator +(Klasse Op) // 'static' is
obligatory!
{
MVector Result;
Result = new Result();
Result.X = this.X + Op.X; //<- but this doesn't work in
'static'!
return Result;
}
}
The C#-Code is not working, because:
1. operator-methods have to be declared as static
2. static methoden my not use 'this'.
Unfortunately I don't find a solution. Can anybody give me a hint?
Thanks,
Lars
Jon Skeet [C# MVP] - 26 Jun 2007 08:06 GMT
On Jun 26, 7:48 am, boe...@sf-systemtechnik.de wrote:
<snip>
> The C#-Code is not working, because:
>
> 1. operator-methods have to be declared as static
> 2. static methoden my not use 'this'.
>
> Unfortunately I don't find a solution. Can anybody give me a hint?
You need to make your operator overload take *two* instances, not just
one:
public static Klasse operator +(Klasse first, Klasse second)
{
MVector Result;
Result = new Result();
Result.X = first.X + second.X;
return Result;
}
(Did you mean to make the type of Result Klasse rather than either
Result or MVector, by the way?)
Jon
Alberto Poblacion - 26 Jun 2007 08:10 GMT
> The C#-Code is not working, because:
>
> 1. operator-methods have to be declared as static
> 2. static methoden my not use 'this'.
>
> Unfortunately I don't find a solution. Can anybody give me a hint?
Operator redefinition is different in C#. In C++ the operator is an
instance method and it operates between the "this" and the received
argument. In C#, the operators are static, and they receive as arguments the
two parameters on which they operate:
public static Klasse operator+(Klasse t1, Klasse t2)
{
Klasse result;
result = new Klasse();
result.X = t1.X + t2.X;
return result;
}