Thread overview | |||||||
---|---|---|---|---|---|---|---|
|
February 26, 2016 how to initialise const variables | ||||
---|---|---|---|---|
| ||||
struct A { const (void *) p; } struct B { A a; this(void * _p) { a.p = _p; } } I cannot change the definition of A how do I initialise b.a.p? |
February 26, 2016 Re: how to initialise const variables | ||||
---|---|---|---|---|
| ||||
Posted in reply to Nicholas Wilson | On Friday, 26 February 2016 at 02:32:44 UTC, Nicholas Wilson wrote:
> struct A
> {
> const (void *) p;
> }
>
> struct B
> {
> A a;
> this(void * _p)
> {
> a.p = _p;
> }
> }
>
> I cannot change the definition of A
> how do I initialise b.a.p?
As you did:
void main() {
int i = 42;
B b = B(&i);
int* p = cast(int*)b.a.p;
assert(*p == 42);
}
|
February 26, 2016 Re: how to initialise const variables | ||||
---|---|---|---|---|
| ||||
Posted in reply to cym13 | On Friday, 26 February 2016 at 02:48:35 UTC, cym13 wrote: > On Friday, 26 February 2016 at 02:32:44 UTC, Nicholas Wilson wrote: >> struct A >> { >> const (void *) p; >> } >> >> struct B >> { >> A a; >> this(void * _p) >> { >> a.p = _p; >> } >> } >> >> I cannot change the definition of A >> how do I initialise b.a.p? > > As you did: > > void main() { > int i = 42; > B b = B(&i); > int* p = cast(int*)b.a.p; > assert(*p == 42); > } > a.p = _p; fails to compile fixed by a = typeof(a)(_p); |
February 26, 2016 Re: how to initialise const variables | ||||
---|---|---|---|---|
| ||||
Posted in reply to Nicholas Wilson | On Friday, 26 February 2016 at 02:32:44 UTC, Nicholas Wilson wrote:
> struct A
> {
> const (void *) p;
> }
>
> struct B
> {
> A a;
> this(void * _p)
> {
> a.p = _p;
> }
> }
>
> I cannot change the definition of A
> how do I initialise b.a.p?
Use a constructor for A instead of trying to write to one specific member:
a = A(_p);
const variable must be initialized in constructors. Structs have automatically defined constructors that take all the member variables so even if it isn't explicitly written, you can still do this.
|
February 26, 2016 Re: how to initialise const variables | ||||
---|---|---|---|---|
| ||||
Posted in reply to Nicholas Wilson | On Friday, 26 February 2016 at 03:18:02 UTC, Nicholas Wilson wrote:
> On Friday, 26 February 2016 at 02:48:35 UTC, cym13 wrote:
>> On Friday, 26 February 2016 at 02:32:44 UTC, Nicholas Wilson wrote:
>>> struct A
>>> {
>>> const (void *) p;
>>> }
>>>
>>> struct B
>>> {
>>> A a;
>>> this(void * _p)
>>> {
>>> a.p = _p;
>>> }
>>> }
>>>
>>> I cannot change the definition of A
>>> how do I initialise b.a.p?
>>
>> As you did:
>>
>> void main() {
>> int i = 42;
>> B b = B(&i);
>> int* p = cast(int*)b.a.p;
>> assert(*p == 42);
>> }
>
>> a.p = _p;
> fails to compile
> fixed by
> a = typeof(a)(_p);
What compiler and version are you using ? Because I literally just copied your example and added my main and got no error.
|
Copyright © 1999-2021 by the D Language Foundation