Re: Array of objects from another class
On Apr 7, 7:24 am, sr98p47 <sr98...@gmail.com> wrote:
I have no experience with C++ other than going through the FAQ to find
my answer but I'm stuck. I did a search on Google Books through
Deitel's C++ book but the preview is limited. I have bought Deitel's
book on C++ on Amazon but it hasn't been delivered yet. There's no
Barnes & Nobles within 50 miles from where we live and the localy
library isn't barren of computer books.
I'm trying to create a simple table in order to start learning C++,
something I can try hashing numbers or characters or strings into. I
don't know much about tables so it's possible I have the concept
wrong.
In my header file, I put the following, leaving out any directives to
save space:
class data {
public:
data(int);
~data(int);
private:
int item;
};
In my definitions file, my constructor is simple:
data::data(int x) {
item = x;
}
I then built another class to create a table, a table consisting of an
array of data items so I can hash numbers or strings into them, but I
don't think I'm constructing it correctly:
Here's my class definition file for the table I want to create:
#include "data.h"
class data_table {
public:
data_table(int);
~data_table();
private:
data *data_entries; // pointer to an arra=
y of data
items.
int table_size;
};
#include "data.h"
data_table::data_table(int size) {
table_size = size;
data_entries = new data[size]; // compiler error
...
}
The warning I'm getting is: no matching function for call to
`data::data()'
I modified my data class definition to include an array, a pointer,
and a copy constructor, but I can't seem to get this to work.
I can stop the compiler errors if I change this
data_entries = new data[size];
to this:
data_entries = new data(size};
but then when I try to write code to access the data_entires array,
there's more compiler errors.
I know I should use a vector, but that's beyond me right now. Is
there a simple solution to this error? I'm sorry if this is an easy
question.
There are few problems in the code
1. ~data(int)-->Destructor do not take any parameter.
2. I am not getting , why you set data::item in constructor. How can
you define all values of hash only at declaration time? The value will
be given by user(hash table user). At that time you will set the value
'item'.
As per my understanding you want to develop data structure like SET in
mathematics. There is already STL 'set' for this purpose. You can use
it if you do not want to write your own code.
If you donot want to use Vector, define constructor as data(int x =
SOME_DEFINE_VALUE) and enjoy 'new'.
3.
a.) data_entries = new data[size];
and
b.) data_entries = new data(size);
are different.
a.) will allocate sizeof(size*data) amount of memory and will call
default constructor.
b.) will allocate sizeof(data) amount of memory and will camm
constructor data(int)