I started programming with C # a few days ago.
Now a confusing error occurs when playing with operator overload.
The following code throws a StackOverflowException :
using System;
namespace OperatorOverloading
{
public class Operators
{
public string text
{
get
{
return text;
}
set
{
if(value != null)
text = value;
else
text = "";
}
}
public Operators() : this("")
{
}
public Operators(string text)
{
this.text = text;
}
public override string ToString()
{
return text;
}
public static string operator +(Operators lhs, Operators rhs)
{
return lhs.text + rhs.text;
}
public static void Main(string[] args)
{
Operators o1 = new Operators();
Operators o2 = new Operators("a");
Operators o3 = new Operators("b");
Console.WriteLine("o1: " + o1);
Console.WriteLine("o2: " + o2);
Console.WriteLine("o3: " + o3);
Console.WriteLine();
Console.WriteLine("o1 + o2: " + (o1 + o2));
Console.WriteLine("o2 + o3: " + (o2 + o3));
}
}
}
I tried to write my own example after reading the chapter on operator overloading from the book "Microsoft Visual C # 2008" by Dirk Louis and Shinji Strasser.
Perhaps someone knows what is going wrong.
Thank.
source
share