АкушерствоАнатомияАнестезиологияВакцинопрофилактикаВалеологияВетеринарияГигиенаЗаболеванияИммунологияКардиологияНеврологияНефрологияОнкологияОториноларингологияОфтальмологияПаразитологияПедиатрияПервая помощьПсихиатрияПульмонологияРеанимацияРевматологияСтоматологияТерапияТоксикологияТравматологияУрологияФармакологияФармацевтикаФизиотерапияФтизиатрияХирургияЭндокринологияЭпидемиология

Operator overloading in C#

Overloaded operators are functions with special names the keyword operator followed by the symbol for the operator being defined. Like any other function, an overloaded operator has a return type and a parameter list.

For example:

public static Box operator+ (Box b, Box c)

{

Box box = new Box();

box.length = b.length + c.length;

box.breadth = b.breadth + c.breadth;

box.height = b.height + c.height;

return box;

}

The above function implements the addition operator (+) for a user-defined class Box. It adds the attributes of two Box objects and returns the resultant Box object.

The overloading is not concerned just with arithmetic operators. We can also consider the comparison operators, ==, <, >,!=, >=, and <=. For example the statement if (a==b). For classes, this statement will, by default, compare the references a and b. It tests to see if the references point to the same location in memory, rather than checking to see if the instances actually contain the same data. For the string class, this behavior is overridden so that comparing strings really does compare the contents of each string. For structs, the == operator does not do anything at all by default. Trying to compare two structs to see if they are equal produces a compilation error unless you explicitly overload == to tell the compiler how to perform the comparison.

Overloading the Conversion operators. We might also need to implement conversion operators sometimes so that our type can safely be converted to and from other types. We can define the conversion operators as implicit or explicit. In case of implicit conversion the user will not have to explicitly type cast our type to target type and our conversion operation will work. In case of explicit conversion the user will have to explicitly cast our type to target type to invoke our conversion operation. If the casting is not performed it will give a compile time error.


Дата добавления: 2015-09-18 | Просмотры: 594 | Нарушение авторских прав



1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 |



При использовании материала ссылка на сайт medlec.org обязательна! (0.003 сек.)