The task
Implement the class in accordance with the variant of the task. The class must contain:
- closed immutable fields that store the state of the class;
- methods for performing operations on class objects. These methods must apply the operation to the current object (this) and the object passed as the argument of the method. To present the result, a new object is created, which is returned from the method. In this case, neither the current object (this) nor the object argument of the method are changed;
- properties that return attributes of the abstraction represented by the class;
- private constructor, taking arguments - field values;
- static construction methods.
Instances of this class must be immutable. The console application is required to demonstrate the use of the developed class.
Need to create
Class: Complex number
State (fields): real and imaginary parts
Design methods: the creation of a complex number in algebraic form, the creation of a complex number in trigonometric form
Properties: real part, imaginary part, module, argument
Operations: addition and subtraction
Here is my code
using System; namespace Complex1 { class Program { static void Main(string[] args) { double re, im, mod, arg; Console.Write("Введите действительную часть комплексного числа re = "); re = Convert.ToDouble(Console.ReadLine()); Console.Write("Введите мнимую часть комплексного числа im = "); im = Convert.ToDouble(Console.ReadLine()); Complex res = new Complex(re, im); } } public class Complex { public Complex() { } public Complex(double _re, double _im) { re = _re; im = _im; } public Complex(double _mod, double _arg) { re = _mod * Math.Cos(_arg); im = _mod * Math.Sin(_arg); } public static Complex operator +(Complex num1, Complex num2) { return new Complex(num1.re + num2.re, num2.im + num2.im); } public static Complex operator -(Complex num1, Complex num2) { return new Complex(num1.re - num2.re, num2.im - num2.im); } public double Re { get; set; } public double Im { get; set; } private double re, im; } }
The first question - I got two constructors with the same signatures, how to solve it?
And I do not understand how to apply p2. methods for performing operations on class objects. These methods must apply the operation to the current object (this) and the object passed as the argument of the method. To present the result, a new object is created, which is returned from the method. In this case, neither the current object (this) nor the object argument of the method are changed; It seems that the use of the keyword this in me is not necessary anywhere.
and p5. Why do I need static constructors here?
Re
,Im
, and the fieldsre
,im
. You initialize only the fields, and the properties both were zeros and remain. Throw out the fields completely, and for the properties prohibit the modification from the outside: public double Re {get; private set; } - VladD amзакрытые неизменяемые поля, хранящие состояние класса;
? - Heidel