原文
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;
}