Listing 4
using namespace System;
public value class Complex
{
double real;
double imag;
public:
static initonly Complex i;
static Complex()
{
i = Complex(0.0, 1.0);
}
Complex(double real)
{
this->real = real;
this->imag = 0.0;
}
Complex(double real, double imag)
{
this->real = real;
this->imag = imag;
}
property double Real
{
double get() { return real; }
void set(double value) { real = value; }
}
property double Imag
{
double get() { return imag; }
void set(double value) { imag = value; }
}
static Complex operator+(Complex z1, Complex z2)
{
return Complex(z1.real + z2.real, z1.imag + z2.imag);
}
static Complex operator-(Complex z1, Complex z2)
{
return Complex(z1.real - z2.real, z1.imag - z2.imag);
}
String^ ToString() override
{
if (imag < 0.0)
{
return String::Format("({0} - {1}i)", real, -imag);
}
else if (1.0/imag == Double::NegativeInfinity)
{
return String::Format("({0} - 0.0i)", real);
}
else
{
return String::Format("({0} + {1}i)", real, +imag);
}
}
};