Access outer member of struct from inner struct

Q. Schroll qs.il.paperinik at gmail.com
Tue Apr 2 18:44:56 UTC 2019


On Tuesday, 2 April 2019 at 18:20:09 UTC, Andrey wrote:
> Hello,
> In this example how can I access the members "read" and "q" of 
> struct Outer from Inner struct?
>> struct Outer
>> {
>> 	ulong q = 1;
>>     Inner inner;
>> 
>>     void read(ulong value)
>>     {
>>         q += value;
>>     }
>> 
>>     void run()
>>     {
>>     	q.writeln;
>>         read(5);
>>     }
>> 
>>     struct Inner
>>     {
>>      	void write(string text)
>>         {
>>             read(text.length);
>>             writeln(q);
>>         }
>>     }
>> }
>> 
>> void main()
>> {
>>     Outer ttt;
>>     ttt.run();
>> }
>
> During compilation I get:
>> onlineapp.d(55): Error: this for read needs to be type Outer 
>> not type Inner
>> onlineapp.d(56): Error: need this for q of type ulong

After removing the calls to writeln, the error I get is:

> `this` for `read` needs to be type `Outer` not type `Inner`

You cannot access stuff in Outer because Inner objects are not 
outer objects and don't implicitly own an Outer object. In your 
Inner method `write`, there is no Outer object present at all to 
call the method on.


More information about the Digitalmars-d-learn mailing list