21.04.2021 16:19, Alain De Vos пишет:
import std.stdio;
void main(){
struct List {
struct Node {
float f;
Node *next;
}
Node * root=null;
bool empty() const {return !root;}
void popFront() {root=root.next;}
float front() const {return root.f;}
void push(float f) {
Node * newnode=new Node();
newnode.f=f;
root.next=newnode; // Segmentation fault
}
}
List * l=new List();
l.push(3);
foreach(element;l){ // Invalid foreach aggregate
writeln(element.root.f);
}
}
```D
import std.stdio;
void main(){
struct List {
struct Node {
float f;
Node *next;
}
Node * root=null;
bool empty() const {return !root;}
void popFront() {root=root.next;}
float front() const {return root.f;}
void push(float f) {
Node * newnode=new Node();
newnode.f=f;
if (root) // by default root is null so you need to
initialize it first time
root.next=newnode;
else
root = newnode;
}
}
List * l=new List();
l.push(3);
foreach(element; *l){ // Invalid foreach aggregate because `l` is a
pointer to List, so you need to dereference the pointer
writeln(element);
}
}
```
1) you need to initialize the root
2) pointer to range is not valid foreach aggregate