On 09/01/2011 04:10 PM, zhang wrote:
Here are some codes:
class AClass
{
int a = 10;
}
struct AStruct
{
AClass aclass;
// this() // can't do this in a struct
// {
// aclass = new AClass()
// }
this(AClass aclass_)
{
aclass = aclass_;
}
}
int main(string[] args)
{
AStruct astruct;
int a = astruct.aclass.a;
writefln("%d", a);
return 0;
}
In D, this() is prohibited in a struct. So
AStruct astruct
will leave the aclass object to be null. It's not like the way in C++, the
aclass object will be created automatically.
It always leads some problems when doing porting from C++ to D.
My solution is to use class instead of struct. Then I can create the aclass
object in this() when I new an AStruct.
Any suggestion?
Thanks.
----------
Zhang<[email protected]>
This works:
class AClass
{
int a = 10;
}
struct AStruct
{
AClass aclass;
// this() @disable; // will be in the next DMD release
static AStruct opCall()
{
return AStruct(new AClass());
}
static AStruct opCall(AClass aclass_)
{
AStruct result = void;
result.aclass = aclass_;
return result;
}
}
int main(string[] args)
{
auto astruct = AStruct();
int a = astruct.aclass.a;
writefln("%d", a);
return 0;
}