I'm not 100% sure what the actual desired behaviour for this program is. There are a couple errors however, which are errors irrelevant to the problem you're trying to solve.
1. First of all you haven't got a default constructor so when you try
(Which I'm guessing you want to initialise an array of type
with the pointer
pointing to the first element. To achieve this you would first have to create a default constructor.
1 2 3 4 5
|
samp()
{
i = int();
j = int();
}
|
(the "int()" just means set the int variable i/j to the default in value, which in this case is 0)
Once you've done this you can create and initialise the array and set the pointer p to point at it. The way i would do it would be
1 2 3
|
samp *p;
samp samps[5] = {};
p = &samps[0];
|
Here i am initialising a pointer of type
but not pointing to anything currently. I then initialise the array of type
with the name
and 5 elements within it. The last line then sets the pointer
to the address of the first element of the array. The "&" symbol is here because p is a pointer so we need an address for the pointer to point to. Using "&" will give the address of a variable rather than the variables value.
If you do not want to use the default constructor and want to set what the array will contain when you initialise it then you would initialise it like
samp samps[5] = {samp(2, 3),samp(3,3),samp(5,6),samp(7,8),samp(8,3)};
This will call the constructor you've got already, with the signature that takes two ints. It will then populate the array with samp objects with the corresponding parameters passed into the constructors i and j values at the current elements index in the array.
2. The other problem here is the line
p[ i ]−>get ( ) ;
The operand square brackets dereferences the pointer at the element stated within it the brackets this means the
shouldn't be treated like a pointer(using the
to access its member functions). Instead because it has been dereferenced it can be treated as an instance of the class
and can have its member functions accessed using a dot "." like you normally would. So the line becomes
p[i].get();
So the final code (Including both initialisation of the array and both constructors so you can select the correct and most helpful method) is put below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
|
#include <iostream>
using namespace std;
class samp
{
private:
int i, j;
public:
samp(int p, int q)
{
i = p;
j = q;
}
samp()
{
i = int();
j = int();
}
void get()
{
cout << i << endl;
cout << j << endl;
}
};
int main()
{
samp *p1;
samp samps1[5] = { samp(2, 3),samp(3,3),samp(5,6),samp(7,8),samp(8,3) }; //Populated array
p1 = &samps1[0];
samp *p2;
samp samps2[5] = { }; //Empty array
p2 = &samps2[0];
if(!p1)
{
cout << "not_enough_memory!" << endl;
return 1;
}
for (int i = 0; i < 5; i++)
p1[i].get();
return 0;
}
|