I am trying to overload operators in a class. But I can't get it to work. The compiler sends me a lot of errors. Like:
CS0019: Operator '`+' cannot be applied to operands of type 'T' and 'T'
or
CS1020: Overloadable binary operator expected
This is my code:
//-------------------------------------------------- public class DataObject<T> { private T data; public static void operator =(DataObject<T> a, T b) { a.data = b; } public static DataObject<T> operator +(DataObject<T> a, DataObject<T> b) { return a.data + b.data; } public static T operator +(DataObject<T> a, T b) { return a.data + b; } } //-------------------------------------------------- public class Int : DataObject<int> { } //-------------------------------------------------- public class Calc { public Int Add(Int a, Int b) { return a + b; } public void Add(Int a, Int b, Int result) { result = a + b; } } //-------------------------------------------------- public class EntryPoint { static void Main() { Int a = new Int(); Int b = new Int(); Int result = new Int(); Calc calc = new Calc(); a = 5; b = 7; calc.Add(a, b, result); Console.Write("\n result=" + result); a = 3; b = 6; result = calc.Add(a, b); Console.Write("\n result=" + result); } }
Could someone tell me how to do this correctly?
Thank you!!
https://stackoverflow.com/questions/67378280/how-to-correctly-overload-operators-in-c May 04, 2021 at 11:06AM
没有评论:
发表评论