d重载共享操作符
public import std.complex;
public interface Mtype
{
// ...
}
public class Number : Mtype
{
public:
this(Complex!realnum=Complex!real(0,0)) shared
//加上共享
{
this.num = num;
}//也要标记为共享.
this(shared Complex!real num = cast(shared Complex!real)Complex!real(0,0))
{//加上共享
this.num.re = num.re;
this.im.re = im.re;
}//共享类,标记所有成员为共享.
Number opBinary(string op)(Number rhs) //标准opBinary
{
mixin("return new Number(this.num " ~ op ~ " rhs.num);");
}
shared(Number) opBinary(string op)(shared Number rhs) shared
{
return new shared Number(); //代码工作前的占位符.
}
package:
Complex!real num;
}
bool isMtype(T)()
{
bool ret = true;
// ...
shared T p = new shared T();
shared T p2 = new shared T();
ret &= __traits(compiles, T, p + p2);
//
return ret;
}
static assert(isMtype!Number); //失败了.
加
shared T c = p + p2
至isMtype
时,得到错误.如何有效
重载共享运算符
并修复它.
另,__traits(compiles)
仅检查表达式
是否语义
正确,而不检查是否编译
,这里不编译.
我加了些额外构造器
,并为Number
的shared
写了个更复杂的opBinary
.现在管用了:
public import std.complex;
public import std.stdio;
public interface Mtype
{
// ...
}
public class Number : Mtype
{
public:
// 新代码开始
this()
{
this.num = Complex!real(1,1);
}
this() shared
{
this.num = Complex!real(1,1);
}
// 新代码结束
this(Complex!real num = Complex!real(0,0))
{
this.num = num;
}
this(shared Complex!real num = cast(shared Complex!real)Complex!real(0,0)) shared
{
this.num.re = num.re;
this.num.im = num.im;
}
Number opBinary(string op)(Number rhs)
{
mixin("return new Number(this.num " ~ op ~ " rhs.num);");
}
shared(Number) opBinary(string op)(shared Number rhs) shared
{//稍微改变这里代码
mixin(q{return new shared Number(Complex!real(this.num.re} ~ op ~ q{rhs.num.re, this.num.im} ~ op ~ q{rhs.num.im));}); //
}
package:
Complex!real num;
}
bool isMtype(T)()
{
bool ret = true;
// ...
shared T p = new shared T();
shared T p2 = new shared T();
ret &= __traits(compiles, T, p + p2);
return ret;
}
static assert(isMtype!Number); //成功了.
void main()
{
shared num1 = new shared Number();
shared num2 = new shared Number();
auto num3 = num1 + num2;
writeln("实: ", num3.num.re, "\n虚: ",num3.num.im);
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现