Problem with operator

B

boeske

Hello,

I have the following C++-Code:

Definition:

class Klasse
{
public:
Klasse operator+(Klasse Op);

public:
int X;
};

Implementation:

Klasse Klasse::blush:perator+(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
 
J

Jon Skeet [C# MVP]

On Jun 26, 7:48 am, (e-mail address removed) wrote:

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
 
A

Alberto Poblacion

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;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top