0
点赞
收藏
分享

微信扫一扫

d构造器不工作


原文

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


举报

相关推荐

0 条评论