let user create their own instances of a class
I want to make it so a user of my Record creating program can create their own records. what is the best way to tackle this?
can i use an array or vec开发者_如何转开发tor for the variable name?
int RecU[100];
class Record
{...};
int main()
{
Record RecU[1];
}
i tried it, and my program is crashing, so im not sure if it is possible.
If you want client code to be able to instantiate Record
at will, all you have to do is ensure that at least one constructor is available to them (or a factory method). Normally this is the case. If you declare your class like this:
class Record
{
};
...then there's nothing to prevent client code from instantiating it. They can simply do this:
int main()
{
Record my_record;
}
In your OP, it looked like you were trying to create an array of 100 Record
s. You do that like this:
class Record
{
};
static const unsigned num_records = 100;
Record the_records[num_records];
int main()
{
for( unsigned i = 0; i < num_records; ++i )
Record& that_record = the_records[i]; // 'that_record' is a ref to one of the records
}
One issue is that you have two definitions of RecU
, which have nothing to do with one another. There's the global one, and there's the one defined in main()
, which hides the global one.
精彩评论