A bit of a conceptual question:
I'm creating my custom structure, in the vein of a Vector3 (3 int values) and I was working through overloading the standard operators (+,-,*, /, == etc...)
As I'm building a library for external use, I'm attempting to conform to FxCop rules. As such, they recommend having methods that perform the same function.
Eg. .Add(), .Subtract(), etc...
To save on code duplication, one of these methods (the operator overload, or the actual method) is going to call the other one.
My question is, which should call which?
Is it (and this is only an example code):
A)
public static MyStruct operator +(MyStruct struc1, MyStruct struct2)
{
return struc1.Add(struct2);
}
public MyStruct Add(MyStruct other)
{
return new MyStruct (
this.X + other.X,
this.Y + other.Y,
this.Z + other.Z);
}
or:
B)
public static MyStruct operator +(MyStruct struc1, MyStruct struct2)
{
return new MyStruct (
struct1.X + struct2.X,
struct1.Y + struct2.Y,
struct1.Z + struct2.Z);
}
public MyStruct Add(MyStruct other)
{
return this + other;
}
I'm really not sure either is preferable, but I'm looking for some opinions :)
This means C++ has the ability to provide the operators with a special meaning for a data type, this ability is known as operator overloading. For example, we can overload an operator '+' in a class like String so that we can concatenate two strings by just using +.
C does not support operator overloading (beyond what it built into the language).
Two operators = and & are already overloaded by default in C++. For example, to copy objects of the same class, we can directly use the = operator. We do not need to create an operator function. Operator overloading cannot change the precedence and associativity of operators.
Operator Overloading is the method by which we can change the function of some specific operators to do some different task. In the above syntax Return_Type is value type to be returned to another object, operator op is the function where the operator is a keyword and op is the operator to be overloaded.
I would go with A). Since operator overloading is not CLS compliant (not all .NET languages support overloading operators) it can be considered as syntactical sugar around the actual Add method.
Either. It really doesn't matter. I'd expect the code to be inlined anyway, so go with whatever you consider more readable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With