feat: Finish part - 4

master
Bobson Lin 5 years ago
parent dd46a13570
commit 342b442622

@ -1,6 +1,7 @@
import 'package:dart_basics/basic_part1.dart' as part1;
import 'package:dart_basics/basic_part2.dart' as part2;
import 'package:dart_basics/basic_part3.dart' as part3;
import 'package:dart_basics/basic_part4.dart' as part4;
main(List<String> arguments) {
// Part 1
@ -14,4 +15,7 @@ main(List<String> arguments) {
// Part 3
part3.basic_operators();
part3.basic_classes();
// Part 4
part4.basic_classes();
}

@ -142,6 +142,3 @@ class Complex {
}
}
}

@ -0,0 +1,69 @@
void basic_classes() {
var n1 = Complex(3, -4);
var n2 = Complex(5, 2);
print(n1 + n2);
print(n1.multiply(n2));
print(Complex.substract(n1, n2));
}
class Complex {
// Private property(member)
num _real;
num _imaginary;
// Getters & Setters
get real => _real;
set real(num newReal) => _real = newReal;
get imaginary => _imaginary;
set imaginary(num newImaginary) => _imaginary = newImaginary;
// Constructors
Complex(this._real, this._imaginary);
Complex.real(num real) : this(real, 0);
Complex.imaginary(num imaginary) : this(0, imaginary);
Complex operator +(Complex c) {
return Complex(this.real + c.real, this.imaginary + c.imaginary);
}
Complex operator *(Complex c) {
return Complex(
(this.real * c.real) - (this.imaginary * c.imaginary),
(this.real * c.imaginary) + (this.imaginary * c.real),
);
}
Complex multiply(Complex c) {
return Complex(
(this.real * c.real) - (this.imaginary * c.imaginary),
(this.real * c.imaginary) + (this.imaginary * c.real),
);
}
static Complex substract(Complex c1, Complex c2) {
return Complex(
c1.real - c2.real,
c1.imaginary - c2.imaginary,
);
}
@override
bool operator ==(dynamic other) {
if (other is! Complex) {
return false;
} else {
return real == other.real && imaginary == other.imaginary;
}
}
@override
String toString() {
if (imaginary >= 0) {
return "$real + ${imaginary}i";
} else {
return "$real - ${imaginary.abs()}i";
}
}
}
Loading…
Cancel
Save