原文
struct Time {
public int hours, minutes, seconds;
this(int h, int m, int s) {
hours = h;
minutes = m;
seconds = s;
}
Time opBinary(string op : "=")(int secos) {
assert(secos <= 86_400);
return new Time(secos / 3600, (secos % 3600) / 60, secos % 60);
}
}
//
module testfortime;
import time;
import std.stdio;
void main() {
Time time = 360;
write(time.hours);
readln;
}
//dmd -run testfortime.d
//不能用(int)調用.
我認為您想要
opAssign
而不是
opBinary
.
還有一個錯誤,因為它是結構,
構造和傳回
它時你不想更新它.
return new Time(secos / 3600, (secos % 3600) / 60, secos % 60);
将傳回
Time*
,而非
Time
.
這樣,更常見:
auto time = Time(360);
//或
const time = Time(360);
//不可指派.
this(int h, int m = 0, int s = 0)
struct Time {
public int hours, minutes, seconds;
// 不需要構造器
void opAssign(int secos) {
assert(secos <= 86_400);
hours = secos / 3600;
minutes = (secos % 3600) / 60;
seconds = secos % 60;
}
}
import std.stdio;
void main() {
auto time = Time(360);
time = 12_345;
writeln(time);
readln;
}