< C++ .NET Operator Overloading 6 | Main | Supplementary Note 1 >


 

 

Operator Overloading 7

 

 

  1. Decimal.op_Division Method

  2. Decimal.op_Equality Method

  3. Decimal.op_GreaterThan Method

  4. Decimal.Parse Method (String, IFormatProvider)

  5. Quick Reference For This Module

 

 

Decimal.op_Division Method

 

Item

Description

Method

Decimal.op_Division

Purpose

Divides two specified Decimal values.

Namespace and assembly

Namespace: System
Assembly: mscorlib (in mscorlib.dll)

Syntax

public:

static Decimal operator / (Decimal d1,  Decimal d2)

Parameters

d1 - A Decimal (the dividend).

d2 - A Decimal (the divisor).

Return value

The Decimal result of d1 by d2.

Example

-

Exceptions

DivideByZeroException - d2 is zero.

OverflowException - The return value is less than MinValue or greater than MaxValue.

 

Table 7

 

The following program example creates several pairs of Decimal values and calculates their quotients with the Division operator.

// operator.cpp : main project file.

// Example of the Decimal multiplication, division, and modulus operators.

#include "stdafx.h"

using namespace System;

 

// Display Decimal parameters and their product, quotient, and remainder.

void ShowDecimalProQuoRem(Decimal Left, Decimal Right)

{

   String^ dataFmt = "   {0,-18}{1,31}";

   Console::WriteLine();

   Console::WriteLine(dataFmt, "Decimal Left", Left);

   Console::WriteLine(dataFmt, "Decimal Right", Right);

   Console::WriteLine(dataFmt, "Left * Right", Left * Right);

   Console::WriteLine(dataFmt, "Left / Right", Left / Right);

   Console::WriteLine(dataFmt, "Left % Right", Left % Right);

}

 

int main(array<System::String ^> ^args)

{

   Console::WriteLine("This example of the Decimal multiplication, division, "

              "and modulus \noperators generates the following "

              "output. It displays the product, \nquotient, and "

              "remainder of several pairs of Decimal objects.");

   // Create pairs of Decimal objects.

   ShowDecimalProQuoRem(Decimal::Parse("1000"), Decimal::Parse("7"));

   ShowDecimalProQuoRem(Decimal::Parse("-1000"), Decimal::Parse("7"));

   ShowDecimalProQuoRem(Decimal(1230000000,0,0,false,7), Decimal::Parse("0.0012300"));

   ShowDecimalProQuoRem(Decimal::Parse("12345678900000000"), Decimal::Parse("0.0000000012345678"));

   ShowDecimalProQuoRem(Decimal::Parse("123456789.0123456789"), Decimal::Parse("123456789.1123456789"));

   return 0;

}

 

Output:

Operator overloading - Example of the Decimal multiplication, division, and modulus operators

 

Decimal.op_Equality Method

 

Item

Description

Method

Decimal.op_Equality

Purpose

Returns a value indicating whether two instances of Decimal are equal.

Namespace and assembly

Namespace: System

Assembly: mscorlib (in mscorlib.dll)

Syntax

public:

static bool operator == (Decimal d1, Decimal d2)

Parameters

d1 - A Decimal.

d2 - A Decimal.

Return value

True if d1 and d2 are equal; otherwise, false.

Example

-

Exceptions

-

 

Table 8

 

Decimal.op_GreaterThan Method

 

Item

Description

Method

Decimal.op_GreaterThan

Purpose

Returns a value indicating whether a specified Decimal is greater than another specified Decimal.

Namespace and assembly

Namespace: System

Assembly: mscorlib (in mscorlib.dll)

Syntax

public:

static bool operator > (Decimal d1,  Decimal d2)

Parameters

d1 - A Decimal.

d2 - A Decimal.

Return value

True if d1 is greater than d2; otherwise, false.

Example

-

Exceptions

-

 

Table 9

 \

The following program example compares several Decimal values to a reference Decimal value using the Greater Than, Equality and other relational operators.

// operator.cpp : main project file.

// Example of the Decimal relational operators.

#include "stdafx.h"

using namespace System;

 

#define dataFmt "{0,43}    {1}"

 

// Compare Decimal parameters, and display them with the results.

void CompareDecimals( Decimal Left, Decimal Right, String^ RightText )

{

  Console::WriteLine();

  Console::WriteLine(dataFmt, String::Concat("Right: ", RightText), Right);

  Console::WriteLine(dataFmt, "Left == Right", Left == Right);

  Console::WriteLine(dataFmt, "Left >  Right", Left > Right);

  Console::WriteLine(dataFmt, "Left >= Right", Left >= Right);

  Console::WriteLine(dataFmt, "Left != Right", Left != Right);

  Console::WriteLine(dataFmt, "Left <  Right", Left < Right);

  Console::WriteLine(dataFmt, "Left <= Right", Left <= Right);

}

 

int main(array<System::String ^> ^args)

{

   Decimal Left = Decimal(123.456);

   Console::WriteLine( "This example of the Decimal relational operators "

   "generates the \nfollowing output. It creates several "

   "different Decimal values \nand compares them with "

   "the following reference value.\n" );

   Console::WriteLine(dataFmt, "Left: Decimal(123.456)", Left);

   // Create objects to compare with a 2-hour Decimal.

   CompareDecimals(Left, Decimal(1.23456E+2), "Decimal(1.23456E+2)");

   CompareDecimals(Left, Decimal(123.4567), "Decimal(123.4567)");

   CompareDecimals(Left, Decimal(123.4553), "Decimal(123.4553)");

   CompareDecimals(Left, Decimal(123456000,0,0,false,6), "Decimal(123456000, 0, 0, false, 6)");

   return 0;

}

 

Output:

 

 

 

 

 

 

 

Operator overloading - Example of the Decimal relational operators

 

Decimal.Parse Method (String, IFormatProvider)

 

Item

Description

Method

Decimal.Parse

Purpose

Converts the String representation of a number to its Decimal equivalent using the specified culture-specific format information.

Namespace and assembly

Namespace: System
Assembly: mscorlib (in mscorlib.dll)

Syntax

public:

static Decimal Parse (String^ s, IFormatProvider^ provider)

Parameters

s - A String containing a number to convert.

provider - An IFormatProvider that supplies culture-specific formatting information about s.

Return value

The Decimal number equivalent to the number contained in s as specified by provider.

Example

 -

Exceptions

ArgumentNullException - s is a null reference (Nothing in Visual Basic).

FormatException - s is not of the correct format

OverflowException - s represents a number less than MinValue or greater than MaxValue

 

Table 10

 

Parameter s contains a number of the form:

[ws][sign]digits[.fractional-digits][ws]

Items in square brackets ('[' and ']') are optional, and other items are as follows.

 

Item

Description

ws

Optional white space.

sign

An optional sign.

digits

A sequence of digits ranging from 0 to 9.

'.'

A culture-specific decimal point symbol.

fractional-digits

A sequence of digits ranging from 0 to 9.

 

Table 11

 

Parameter s is interpreted using the NumberStyles.Number style. Parameter provider is an IFormatProvider that obtains a NumberFormatInfo. The NumberFormatInfo provides culture-specific information about the format of s. If provider is a null reference (Nothing in Visual Basic), the NumberFormatInfo for the current culture is used. A Decimal has 29 digits of precision. If s represents a number that has more than 29 digits, but has a fractional part and is within the range of MaxValue and MinValue, the number is rounded, not truncated, to 29 digits using rounding to nearest. The following code example parses String representations of Decimal values with several overloads of the Parse method.

// operator.cpp : main project file.

// Example of the Decimal::Parse() methods.

#include "stdafx.h"

 

using namespace System;

using namespace System::Globalization;

using namespace System::Collections;

 

// Parse each string in the decimalFormats array, using

// NumberStyles and IFormatProvider, if specified.

void DecimalParse(NumberStyles styles, IFormatProvider^ provider)

{

   array<String^>^decimalFormats = gcnew array<String^>(6);

   decimalFormats[ 0 ] = "9876543210.9876543210";

   decimalFormats[ 1 ] = "9876543210,9876543210";

   decimalFormats[ 2 ] = "(9876543210,9876543210)";

   decimalFormats[ 3 ] = "9,876,543,210,987,654.3210";

   decimalFormats[ 4 ] = "9.876.543.210.987.654,3210";

   decimalFormats[ 5 ] = "98_7654_3210_9876,543210";

   // Code foreach(String* decimalString in decimalFormats).

   IEnumerator^ myEnum = decimalFormats->GetEnumerator();

   while (myEnum->MoveNext())

   {

      String^ decimalString = safe_cast<String^>(myEnum->Current);

      Decimal decimalNumber;

      // Display the first part of the output line.

      Console::Write("  Parse of {0,-29}", String::Format("\"{0}\"", decimalString));

      try

      {

         // Use the appropriate Decimal::Parse overload, based

         // on the parameters that are specified.

         if (provider == nullptr)

           if ((int)styles < 0)

             decimalNumber = Decimal::Parse(decimalString);

           else

             decimalNumber = Decimal::Parse(decimalString, styles);

           else

           if ((int)styles < 0)

             decimalNumber = Decimal::Parse(decimalString, provider);

           else

             decimalNumber = Decimal::Parse(decimalString, styles, provider);

           // Display the resulting value if Parse succeeded.

           Console::WriteLine("succeeded: {0}", decimalNumber);

       }

       catch (Exception^ ex)

       {

           // Display the exception message if Parse failed.

           // Truncate it to fit on the output line.

           Console::WriteLine("failed: {0}", ex->Message->Substring(0, 31));

       }

   }

}

 

int main(array<System::String ^> ^args)

{

   Console::WriteLine("This example of\n"

         "  Decimal::Parse(String*),\n"

         "  Decimal::Parse(String*, NumberStyles),\n"

         "  Decimal::Parse(String*, IFormatProvider* ), and\n"

         "  Decimal::Parse(String*, NumberStyles, "

         "IFormatProvider*)\ngenerates the "

         "following output when run in the [{0}] culture.", CultureInfo::CurrentCulture->Name);

   Console::WriteLine("Several string representations "

          "of Decimal values are parsed.");

   // IFormatProvider and NumberStyles are not used.

   Console::WriteLine("\nNumberStyles and IFormatProvider are not "

          "used; current culture is [{0}]:", CultureInfo::CurrentCulture->Name);

   DecimalParse((NumberStyles)(-1), nullptr);

   // Use the NumberStyle for Currency.

   Console::WriteLine("\nNumberStyles::Currency "

          "is used; IFormatProvider is not used:");

   DecimalParse(NumberStyles::Currency, nullptr);

   // Create a CultureInfo object for another culture. Use

   // [Dutch - The Netherlands] unless the current culture

   // is Dutch language. In that case use [English - U.S.].

   String^ cultureName = CultureInfo::CurrentCulture->Name->Substring(0, 2) == "nl" ? (String^)"en-US" : "nl-NL";

   CultureInfo^ culture = gcnew CultureInfo(cultureName);

   Console::WriteLine("\nNumberStyles is not used; [{0}] "

         "culture IFormatProvider is used:", culture->Name);

   DecimalParse((NumberStyles)(-1), culture);

   // Get the NumberFormatInfo object from CultureInfo, and

   // then change the digit group size to 4 and the digit

   // separator to '_'.

   NumberFormatInfo^ numInfo = culture->NumberFormat;

   array<Int32>^sizes = {4};

   numInfo->NumberGroupSizes = sizes;

   numInfo->NumberGroupSeparator = "_";

   // Use the NumberFormatInfo object as the IFormatProvider.

   Console::WriteLine("\nNumberStyles::Currency is used, "

          "group size = 4, separator = \"_\":");

   DecimalParse(NumberStyles::Currency, numInfo);

   return 0;

}

 

Output:

Oeprator overloading - Example of the Decimal::Parse( ) methods.

 

Quick Reference For This Module

 

To

Do this

Overload operators for value types.

Implement the appropriate operator function as a static member of the type.

Implement equality tests.

Overload == and !=, and provide an overload of Equals for the benefit of other .NET languages.

Overload operators for reference types.

Use pointers for argument and return types.

 

Table 12

 

 

 

 

 

 

Part 1 | Part 2 | Part 3 | Part 4 | Part 5 | Part 6 | Part 7

 


 

< C++ .NET Operator Overloading 6 | Main | Supplementary Note 1 >