Arrays of classes
Part of ArraysCategory
Description
How to allocate arrays of classes and pass them to functions.
Example
import std.c.stdio; import std.string; class A { int n; this(int n1) { n = n1; // we are in the constructor printf("Constructor (n = %d)\n", n); } // operator to convert class A to a string char[] toString() { char[] ris; ris = .toString(n); return ris; } } void Print(A[] a) { // print all the elements of array "a" for (int i = 0; i < a.length; i++) { printf("A%.*s\n", .toString(a[i].n)); } } int main(char[][] args) { A[] a; // allocate the memory a.length = 5; // i is a counter, j gets a pointer to A foreach (int i, A j; a) { // allocate the element j and copy the reference to a[i] a[i] = j = new A(i); printf("A%.*s\n", j.toString()); } Print(a); return 0; }
Source
Link | http://www.dsource.org/tutorials/index.php?show_example=151 |
Posted by | Anonymous |