Reputation: 2461
I am trying to create a dynamic array of objects, using a static variable as a pointer to the next available array index. I'm sure there is a better way to do this...
class storing the dynamic array:
import std.stdio;
import DataRow;
class Database{
public:
this(){ /* intentionally left blank */}
void addRow(DataRow input){
this.db[count] = input;
writeln(count);
count++;
}
private:
static uint count;
DataRow[] db;
}
Upvotes: 0
Views: 153
Reputation: 7198
D arrays can be appended to with the ~=
operator, and keep track of their own length
. You shouldn't need to keep track of the length yourself:
void addRow(DataRow input){
this.db ~= input;
writeln(db.length); // number of rows in db
}
Based on your example, I'm not sure if this is what you intended. Each Database
instance has its own member db
, but all would share the same count
variable as you declared it as static
.
Unless you have a good reason for keeping a static counter (which would track the number of rows added across all instances of Database
), I would just rely on each array to track its own length.
Upvotes: 2