Reputation: 29
I have problem with pointers. My classes:
Zbior{
Czasteczka* tablicaCzasteczek; //it will be a pointer to dynamic array
Zbior();
}
Czasteczka{
Czasteczka();
Czasteczka(int x, int y);
}
Constructor of Zbior:
Zbior::Zbior()
{
this->tablicaCzasteczek = new Czasteczka[n];
for( int i=0 ; i<n ; i++ )
{
this->tablicaCzasteczek[i] = NULL; <-- here is 1st error
}
this->tablicaCzasteczek[0] = new Czasteczka(X, Y); <-- 2nd error
this->tablicaCzasteczek[1] = new Czasteczka(X, Y+1); <-- same error as above
}
Above code has to create dynamic array and add first and second object to this array.
Errors:
1.) Error 4 error C2679: binary '=' : no operator found which takes a right-hand operand of type 'int' (or there is no acceptable conversion)
2.) Error 6 error C2679: binary '=' : no operator found which takes a right-hand operand of type 'Czasteczka *' (or there is no acceptable conversion) Thank for all help! :)
Upvotes: 0
Views: 134
Reputation: 5525
Czasteczka *tablicaCzasteczek
is a pointer to an instance of Czasteczka
. It can also be holding a pointer to the first element of a decayed array of Czasteczka
. This is the crucial part to understand:
tablicaCzasteczek[0] = NULL;
is equivalent to *tablicaCzasteczek = NULL
. That means you're trying to assign NULL to an instance of Czasteczka
.
If you really want to make your code work, declare tablicaCzasteczek
as
Czasteczka **tablicaCzasteczek;
and later on
this->tablicaCzasteczek = new Czasteczka*[n];
But that is calling for trouble if you don't know what you're doing (I don't see any destructors in your example).
As others have suggested, you'll be having much less headaches if you use std::vector. You'd be much better off with something like this:
class Czasteczka
{
public:
Czasteczka(int x, int y);
Czasteczka(const Czasteczka &other);
};
std::vector <Czasteczka> zbiorCzasteczek;
And then if you're on C++11:
zbiorCzasteczek.emplace_back(someX, someY);
Or if you're not:
zbiorCzasteczek.push_back(Czasteczka(someX, someY));
You can then access you're elements just as you would with an array (zbiorCzasteczek[0]
). In this case, you won't have to worry about memory management, as std::vector
will take care of that for you.
Of course you can put the vector as your class' member as well. I left out your Zbior
class, as in your example it didn't do anything in particular.
Upvotes: 2