Fre*_*rik 4 d operator-overloading dmd
我似乎在我的一个类中重载opIndexAssign时遇到了一些麻烦.
我上课了; JSObject的定义如下:
alias char[] String;
Run Code Online (Sandbox Code Playgroud)
...
class JSObject : Dobject
{
/*****************************************************************
* Constructors
******************************************************************/
this( Dobject dobj )
{
super( dobj ) ;
}
this()
{
super( null ) ;
}
this( AssociativeArray data )
{
// initiate
super( null ) ;
// then populate
foreach( k, v ; data )
{
this[ k ] = v ;
}
}
public void opIndexAssign( String key , String val )
{
Value* v = new Value() ;
v.putVstring( val ) ;
this.Put(key, v , DontDelete);
}
public void opIndexAssign( String key , Dobject dobj )
{
Value* v = new Value() ;
v.putVobject( dobj ) ;
this.Put(key, v , DontDelete);
}
public void opIndexAssign( String key , JSObject jso )
{
Value* v = new Value() ;
v.putVobject( jso ) ;
this.Put(key, v , DontDelete);
}
public Value* opIndex( String key )
{
return this.Get( key );
}
}
Run Code Online (Sandbox Code Playgroud)
Dobject超类重载了put()和get()方法,我试图将它们包装起来,以便我可以将它们作为关联数组访问:
77: JSObject jso = new JSObject() ;
78: jso[ "foo" ] = "bar" ;
79:
80: JSObject jsoParent = new JSObject() ;
81: jsoParent[ "child" ] = jso ;
Run Code Online (Sandbox Code Playgroud)
它适用于String,String方法但是当我尝试使用JSObject作为值时,它会失败.
test2.d => test2
+ c:\dmd\dsss\bin\rebuild.exe -version=PhobosCompatibility -w -Idsss_imports\ -I. -S.\ -Ic:\dmd\dsss\include\d -Sc:\dmd\dsss\lib\ -Ic:\dmd\dsss\include\d -Sc:\dmd\dsss\lib -oqdsss_objs\D -debug -gc test2.d -oftest2
test2.d(81): Error: function dmdscripttest.JSObject.opIndexAssign (char[],char[]) does not match parameter types (JSObject,char[5u])
test2.d(81): Error: cannot implicitly convert expression (jso) of type dmdscripttest.JSObject to char[]
test2.d(81): Error: cannot implicitly convert expression ("child") of type char[5u] to dmdscripttest.JSObject
Error: Command failed, aborting.
Command c:\dmd\dsss\bin\rebuild.exe returned with code 1, aborting.
Run Code Online (Sandbox Code Playgroud)
我有点不知所措.这就像编译器试图将其转换为适合opIndexAssign(String,String)而不是opIndexAssign(String,JSObject)方法.
我是否错误地定义了opIndexAssign函数?
提前致谢,
问题是opIndexAssigne首先需要值,然后需要键(或索引)
http://www.d-programming-language.org/operatoroverloading.html#Assignment
所以你要把它定义为
public void opIndexAssign( String val , String key)
{
Value* v = new Value() ;
v.putVstring( val ) ;
this.Put(key, v , DontDelete);
}
public void opIndexAssign( Dobject dobj , String key)
{
Value* v = new Value() ;
v.putVobject( dobj ) ;
this.Put(key, v , DontDelete);
}
public void opIndexAssign( JSObject jso , String key)
{
Value* v = new Value() ;
v.putVobject( jso ) ;
this.Put(key, v , DontDelete);
}
Run Code Online (Sandbox Code Playgroud)
这样做的原因是你可以为索引定义一个vararg
| 归档时间: |
|
| 查看次数: |
322 次 |
| 最近记录: |