toString and opEquals
Let’s learn about toString and opEquals functions for classes.
toString
Same with structs, toString
enables using class objects as strings. The following code shows how toString()
is implicitly called when displaying class objects:
Press + to interact
import std.stdio;class Clock {int hour;int minute;int second;this(int hour, int minute, int second) {this.hour = hour;this.minute = minute;this.second = second;}}void main() {auto clock = new Clock(20, 30, 0);writeln(clock); // Calls clock.toString()}
The inherited toString()
is usually not useful; it produces just the name of the type:
deneme.Clock
Here deneme
is the name of the module. The output above indicates that Clock
has been defined in the deneme
module.
As we have seen in the previous chapter, this function is almost always overridden to produce a more meaningful string representation of an object:
Press + to interact
import std.string;import std.stdio;class Clock {int hour;int minute;int second;this(int hour, int minute, int second) {this.hour = hour;this.minute = minute;this.second = second;}override string toString() const {return format("%02s:%02s:%02s", hour, minute, second);}// ...}class AlarmClock : Clock {int alarmHour;int alarmMinute;this(int hour, int minute, int second,int alarmHour, int alarmMinute) {super(hour, minute, second);this.alarmHour = alarmHour;this.alarmMinute = alarmMinute;}override string toString() const {return format("%s ♫%02s:%02s", super.toString(),alarmHour, alarmMinute);}// ...}void main() {auto bedSideClock = new AlarmClock(20, 30, 0, 7, 0);writeln(bedSideClock);}
opEquals
As we have seen in the ...