struct implements IComparable : Definition « Structure « Visual C++ .NET

Home
Visual C++ .NET
1.2D
2.Class
3.Collections
4.Data Type
5.Database ADO.net
6.Delegate
7.Development
8.File Directory
9.Function
10.Generics
11.GUI Form
12.Language Basics
13.Network
14.Reflection
15.Security
16.Statement
17.Structure
18.Thread
19.XML
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Visual C++ .NET » Structure » Definition 
struct implements IComparable
 
#include "stdafx.h"
using namespace System;
using namespace System::Collections;
using namespace System::Globalization;

public value struct Vector: public IComparable
{
    property double X;
    property double Y;

    property double Magnitude
    {
        double get()
        {
            return Math::Sqrt(X*X + Y*Y);
        }
    }

    virtual int CompareTo(Object^ obj)
    {
        Vector^ v = *dynamic_cast<Vector^>(obj);
        if )
        {
            if this->Magnitude == v->Magnitude )
                return 0;
            else if this->Magnitude < v->Magnitude )
                return -1;
            else
                return 1;
        }
        else
            throw gcnew ArgumentException(
                "Vector::CompareTo: obj must be of type 'Vector'");
    }
    // Comparison operators
    static bool operator ==(Vector a, Vector b)
    {
        return a.X == b.X && a.Y == b.Y;
    }
    static bool operator !=(Vector a, Vector b)
    {
        return a.X != b.X || a.Y == b.Y;
    }
    static bool operator >(Vector a, Vector b)
    {
        return a.Magnitude > b.Magnitude;
    }
    static bool operator <(Vector a, Vector b)
    {
        return a.Magnitude < b.Magnitude;
    }

    // Misc required overloads
    virtual bool Equals(Object^ objoverride
    {
        Vector^ compareTo = dynamic_cast<Vector^>(obj);
        if compareTo )
        {
            return *this == *compareTo;
        }
        else
        {
            return false;
        }
    }
    virtual int GetHashCode() override
    {
        return X.GetHashCode() ^ Y.GetHashCode();
    }
    virtual String^ ToString() override
    {
        return String::Format(CultureInfo::CurrentCulture->NumberFormat,
            "[{0}, {1}]", X, Y);
    }
};


void main()
{
    array<Vector>^ data = gcnew array<Vector>(10);

    // Sorting test
    Random^ random = gcnew Random();
    for int i = 0; i < data->Length; i++ )
    {
        data[i].X = random->NextDouble();
        data[i].Y = random->NextDouble();
    }

    Array::Sort(data);

    for int i = 0; i < data->Length; i++ )
    {
        Console::WriteLine("data[{0}]={1}", i, data[i].Magnitude);
    }
}

   
  
Related examples in the same category
1.Declare a Structure Type
2.Create a Structure
3.Initialize a Structure
4.Access a Structure
5.Complex struct
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.