J
It's not such a simple task. I mean, she can't be solved stupidly. It's much easier for me not to mess up the code, but to rewrite it. So what's the problem:C# does not support the overloading of many operators. But like the operators you've identified can be overloaded.The indexes in control C# are prohibited. But this is not a problem, all copies of objects and structures are references ( " C+++ " ).Just so you don't do all the work for you. The code itself is written (as C++ cannot be advertised, announced and defined by the method should be in one place) //к сожалению в структурах запрещены циклические ссылки, но ими никто в c# не пользуется
//имена классов и членов с большой буквы (так принято)
class Element
{
//не данные, а свойства (так принято)
//но если не нужно, можно убрать '{ get; set; }'
public char A { get; set; }
public Element Next { get; set; }
};
class List
{
//нельзя как в c++ писать 'public:', вы должны перед каждым методом писать 'public'
//private - по умолчанию, его можно не писать
//конструктор
public List()
{
}
//деструкторов в c# нет: тут автоматическая сборка мусора
//~list();
/// <summary>
/// Коментарии в таком прикольном виде пишем
/// Добавление элемента в список
/// </summary>
/// <param name="c">данные</param>
public void Add(char c)
{
}
//не могу написать оператор, вместо него будет функция
//public explicit List(char c)
public void CreateFromChar(char c)
{
}
//оказывается все операторы должны быть статические, так что добавляем List в первый аргумент
//вроде не ругается, но я бы через функцию сделал
public static List operator +(List l, char c)
{
return null;
}
public static List operator --(List l)
{
return null;
}
public static bool operator ==(List l1, List l2)
{
return false;
}
//оператор '==' должен быть вместе с '!='
public static bool operator !=(List l1, List l2)
{
return true;
}
//эти два метода тоже придется реализовать, иначе на '==' ругается
public override bool Equals(object obj)
{
return base.Equals(obj);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
public void Print()
{
}
//приватные члены, можем ключевое слово 'private' опустить
//опять же оформил как свойства, но можем и как обычные данные сделать
Element Head { get; set; }
int Count { get; set; }
}
Update: and GetHashCodeThese are two different methods to support comparison operations in C#, they have no similarities in C+++. The simplest is equals. He accepts another object of the same type and returns true if the object is equal to this and false, if not equal. The logic of the method is your business. It can be assumed that this method is the same as the operator '=' in C+++.class List
{
public override bool Equals(object obj)
{
return true; //напишите здесь правильное сравнение (можно вызвать '==')
}
}
List l1 = new List();
List l2 = new List();
Console.WriteLine(l1.Equals(l2)); //true
//можно было бы написать 'l1 == l2',
//но из-за присутствия оператора '==' в классе, метод Equals не вызовется
GetHashCode() - has no equivalent in C++. In the C#, it's necessary for the right work of vocabularies, but it's an association. The consignor keeps objects in line with their keys and the keys in C# are numbers. In JavaScript, for example, the keys are rows. In your case, you can realize GetHashCode() as the GetHashCode(s) association for each element List:public override int GetHashCode()
{
var e = this.Head;
int res = 0;
int mul = 1;
while (e != null)
{
res += e.A.GetHashCode() * mul;
e = e.Next;
mul *= 17; //волшебное число
}
return res;
}
var l1 = new List();
l1.Add('a');
l1.Add('b');
var l2 = new List();
l2.Add('b');
l2.Add('a');
var d = new Dictionary<List, bool>();
d.Add(l1, true);
Console.WriteLine(d.ContainsKey(l1)); //true
Console.WriteLine(d.ContainsKey(l2)); //false