I wrote the code below:
Code |
One of the parameters of a binary operator must be the containing type
What's the problem?
Thanks.
Code |
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Sam HobbsRank #107 · 20.5K reputationPosted Aug 9, 2010, 9:34 AM EDT
That is not the way that most object-oriented languages work. In C# you can create Extension methods; look at the documentation of those.
Kirtan PatelRank #292 · 8.6K reputationPosted Aug 8, 2010, 7:30 AM EDT
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();
}
Majid KamaliRank #6,453 · 266 reputationPosted Aug 8, 2010, 10:10 AM EDT
But Can I overload an operator for a predefined class ?
If yes, Why it Creates Error ?
Kirtan PatelRank #292 · 8.6K reputationPosted Aug 8, 2010, 11:54 AM EDT
if it allows then you can inherit it and can overload operator in that derived class
Hope it helps you :)
Majid KamaliRank #6,453 · 266 reputationPosted Aug 8, 2010, 12:38 PM EDT
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 PatelRank #292 · 8.6K reputationPosted Aug 8, 2010, 6:46 PM EDT
Majid KamaliRank #6,453 · 266 reputationPosted Aug 8, 2010, 11:08 PM EDT
Kirtan PatelRank #292 · 8.6K reputationPosted Aug 9, 2010, 4:00 AM EDT
Majid KamaliRank #6,453 · 266 reputationPosted Aug 9, 2010, 5:50 AM EDT