I wrote the code below:
|
One of the parameters of a binary operator must be the containing type
What's the problem?
Thanks.
|
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Sam HobbsPosted Aug 9, 2010, 1:34 PM
That is not the way that most object-oriented languages work. In C# you can create Extension methods; look at the documentation of those.
Majid KamaliPosted Aug 9, 2010, 9:50 AM
Kirtan PatelPosted Aug 9, 2010, 8:00 AM
Majid KamaliPosted Aug 9, 2010, 3:08 AM
Kirtan PatelPosted Aug 8, 2010, 10:46 PM
Majid KamaliPosted Aug 8, 2010, 4:38 PM
I don't want to modify it's private members. I just want to create a new point and add new X and Y to it's members.
Kirtan PatelPosted Aug 8, 2010, 3:54 PM
if it allows then you can inherit it and can overload operator in that derived class
Hope it helps you :)
Majid KamaliPosted Aug 8, 2010, 2:10 PM
But Can I overload an operator for a predefined class ?
If yes, Why it Creates Error ?
Kirtan PatelPosted Aug 8, 2010, 11:30 AM
do check "Do you like this answer" checkbox if it helps you :)
class CartsianPoint
{
private int x;
private int y;
public CartsianPoint()
{
}
public CartsianPoint(int x, int y)
{
this.x = x;
this.y = y;
}
public static CartsianPoint operator +(CartsianPoint p1,CartsianPoint p2)
{
CartsianPoint temp = new CartsianPoint(p1.X+p2.X,p1.Y+p2.Y);
return temp;
}
public int X
{
get{return x;}
set{x = value;}
}
public int Y
{
get { return y; }
set { y = value; }
}
}
I used like below in Main Method
static void Main(string[] args)
{
CartsianPoint p1 = new CartsianPoint(10,10);
CartsianPoint p2 = new CartsianPoint(20, 20);
CartsianPoint result = p1 + p2;
Console.WriteLine("p3 X:=" + result.X+" and p3 Y="+result.Y);
Console.ReadKey();
}