Tutorials to .com

Tutorials to .com » Dotnet » Oop » Help me, I overloading (C #)

Help me, I overloading (C #)

Print View , by: iSee ,Total views: 27 ,Word Count: 2076 ,Date: Tue, 21 Apr 2009 Time: 7:49 PM

As the c # language specification On the continuation of this month we will discuss the issue of operator overloading. Operator overloading (unless specified, otherwise the rest of this column will be referred to as "heavy") allows the user to refer to the type of user-defined expression of the ability of the preparation. It allows user-defined types and the type of pre-defined function with the same.

For example, often need to write code like the following to add the two figures. Obviously, sum of two figures.

int i = 5;
int sum = i + j;

If you can use on behalf of the user-defined complex types to the preparation of the same type of expression, of course, it better and better:

Complex i = 5;
Complex sum = i + j;

Operator overloading allows user-defined types for heavy-duty (that is, the meaning specified explicitly), such as "+" such operator. If not overloaded, the user need to write the following code:

Complex i = new Complex (5);
Complex sum = Complex.Add (i, j);

This code can be run well, but the Complex type as the language does not pre-defined type as a role to play.

Have anything specific time and place is a heavy-duty operator easily lead to misunderstanding of language features, and programmers to treat it different attitude. Some people think that: the preparation of this feature users will be hard to understand the process, and it should not be attributed to programming languages. others think it is a very good function can be used anywhere.

These two views are included elements of the right, but there are also defects. It should be recognized that operator overloading may lead to the preparation of puzzling out the procedure, but according to my experience, even if it does not use operator overloading, it is likely to produce the code hard to understand. In some cases, do not use heavy-duty code, they can lead to a more puzzling.

Regardless of those occasions, the people free to use heavy-duty "really" in production code is difficult to understand.

The reason why the language used in heavy-duty, is to the concept of users or the structure can be simplified. Only help to improve the readability of the code written by the user, the operator can be overloaded. Please note that we are talking about the test, "more clarity" rather than "shorter." Use of the category of operator overloading code will almost always become more brief, but it does not always make the code more clear (ie, readability).

To illustrate this point, I created a number of heavy-duty sample. You need to carefully read the code, think about which operator to carry out a heavy-duty, heavy-duty operator of any operation carried out.

Test
1
BigNum n1 = new BigNum ( "123456789012345");
BigNum n2 = new BigNum ( "11111");
BigNum sum = n1 + n2;

B
Matrix m1 = loadMatrix ();
Matrix m2 = loadMatrix ();
Matrix result = m1 * m2;

iii
DBRow row = query.Execute ();
while (! row.Done)
(
Viewer.Add (row);
row + +;
)

IV
Account current = findAccount (idNum);
current + = 5;

Answer and discussion
1
This example, it is necessary to perform an operation that is obvious. This addition will only add up to a predefined type, that everyone understands what the implementation of computing, so in this example, the use of operator overloading makes sense.

B
This example to demonstrate how to multiply matrices. Conceptually, the conventional multiplication matrix multiplication is not completely similar, but it is a clear definition of the operator, so that any understanding of matrix multiplication of the people to see this overloaded operator, they would not be surprised.

iii
This example, increment (+ +) operator for the heavy-duty, which allows the database to move forward in the next line line. database relating to any of the things that we can not understand the true meaning of this incremental, and incremental to perform this operation is not so obvious.

In this example, the use of heavy-duty did not make the code easier. If we instead use the following code, the situation is much better:

DBRow row = query.Execute ();
while (! row.MoveNext ())
(
Viewer.Add (row);
)

IV
Things and employees will be the sum of what the meaning of this? This example, choose to be a good way to add up the number of its employees will be registered employees. This is a very bad use of operator overloading.

The timing of the principle of the principle of overload is relatively simple. If the user wants to carry out such operations, it should be heavy.

Overloading Arithmetic Operators in C++ # to overload the operator to specify a function to perform operations on it. Function must be the type of operations involved in the definition of, and at least one of the parameters are of this type. This prevents the addition of int or other strange things to overloading.

To demonstrate the heavy, we will develop a vector. Vector can be considered from the point of origin to a specific two-dimensional line. Can perform a variety of vector operations. The following is a rough definition of this type:

struct Vector
(
float x;
float y;

public Vector (float x, float y)
(
this.x = x;
this.y = y;
)
)

To practical use, the vector should support the following operations:

access to the length of the vector will be multiplied by a vector divided by the number of a vector sum of the two figures will be less of a vector to another vector of the point of calculating the vector product of two of our task is to determine how to achieve these calculations.

Vector length for the length of access, does not seem to have any meaningful operator. Length will not change, so it is of great significance as an attribute:

public float Length
(
get
(
return ((float) Math.Sqrt (x * x + y * y));
)
)

Will be multiplied by the vector / vector divided by a number will be multiplied by a number is a very common operation, and computing the user wants to achieve. The following is the relevant code:

public static Vector operator * (Vector vector, float multiplier)
(
return (new Vector (vector.x * multiplier,
vector.y * multiplier));
)

It should be noted that here there are many interesting phenomenon. First of all, the operator is a static function, it must obtain the value of two parameters, while results must return a new object. Operator is exactly the name of "operator", to be followed behind the overloaded operator.

Divided by a number of similar code and the code above.

Addition and subtraction of two vectors for this is a very common vector operation, so it is clear to them overloaded.

public static Vector operator + (Vector vector1, Vector vector2)
(
return (new Vector (vector1.x + vector2.x,
vector1.y + vector2.y));
)

Subtraction of the code is very similar to the above code.

Calculation of point-point plot of the two vectors for the vector plot is the definition of special operations in the pre-defined types can not be found with similar operations. In the equation, the plot points in between the two vectors to express a point to write it and any existing operator is not the exact match. An interesting plot points are: it is to obtain the value of the two vectors, but only to return to a simple figure.

Whether or not to carry out the heavy-duty computing, users are more or less the same code. The first line shows the heavy-duty version in use, the other line shows the two alternative versions:

double v1i = (velocity * center) / (t * t);
double v1i = Vector.DotProduct (velocity, center) / (t * t);
double v1i = velocity.DotProduct (center) / (t * t);

At this point, it is almost a call to judge. I prepared the class for "*" a heavy-duty operator for point multiplication operations, but reflect back, I think this code is not the most appropriate code.

In the first example, velocity vector, and this center is not very clear, therefore, the plot points is to perform an operation that is not very clear (I use it to find an example, the notes of this). The second example illustrates very clearly what operation to perform, I think using the example of the code is best for them.

The third example also, but I think that, if not a member of the computing function, the code will be more clearer.

public static double DotProduct (Vector v1, Vector v2)
(
return (v1.x * v2.x + v1.y * v2.y);
)

C # and C + + overloading and C + + compared, C # allows operator overloading of the few. There are two restrictions. First of all, the members visit the members call (that is, function calls), the assignment and the "new" can not be overloaded, because these calculations is the definition of run-time.

Secondly, as this "&&","||","?:" operator such as "+ =" This compound can not be overloaded assignment operator, because it would become very complex code more losses than gains.

Conversion of heavy-duty so that we return to the original sample:

Complex i = 5;
Complex sum = i + j;

Although it is known how to add heavy-duty operator, but we need to make in order to play a role in the first sentence. This can be carried out on the conversion to achieve overload.

Implicit and Explicit Conversion
C # supports both implicit and explicit conversion. Implicit conversion is always that the successful implementation of the conversion, and the reasons for its success are usually target type is equal to or greater than the scope of the scope of the source types. From short to int conversion is an implicit conversion. Implicit conversion can be used as part of assignment statements:

short svalue = 5;
long lvalue = svalue;

Explicit conversions are those that could cause data loss or conversion of an exception is raised. Therefore, the explicit requirements of the mandatory conversion to the type of conversion:

long lvalue = 5;
short svalue = (short) lvalue;

Overloading of the conversion should be decided to conversion is implicit or explicit, but implicit conversion should be aware that the model is safe, and explicit conversion is risky.

The integer value 5 converted to the definition of plural conversion as follows:

public static implicit operator Complex (int value)
(
return (new Complex (value, 1.0));
)

This allows for Complex from int to the implicit conversion.

Language interoperability is more than C # in the overloaded operator for the situation. When related to other languages, things will become somewhat complicated.

Operator is not overloaded. NET common language subset of one of the functions, which means that in some languages will not be able to use heavy-duty. It is important to provide an alternative to non-heavy-duty is very important, so in other languages can still perform the same operation. If you add the class definition of the operator, it should be defined the same way,
Add the use of similar names such as naming.


.Net Object Oriented Programming Articles


Can't Find What You're Looking For?


Rating: Not yet rated

Comments

No comments posted.