Jump to content
  • Advertisement

Archived

This topic is now archived and is closed to further replies.

Krisc

c++ error, vector of classes

This topic is 5555 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi, I have a vector of classes, and I need to initialize each one... so when I declare my vector I do apvector b(0); this declares a vector of buildings of size 0. now, when I want to initialize each one, what do i do? b.resize(1); //resize the vector b[0] = building("building name", 5); this gets an error of "Call of nonfunction" any ideas?

Share this post


Link to post
Share on other sites
Advertisement
Two possibilities:

  1. Use an array of pointers, or...
  2. Make sure your objects have a copy constructor/assignment operator and copy them into the vector.


For the latter:

class Foo
{
public :
//Constructor

Foo (int i)
{
m_num = i;
}

//Copy constructor

Foo (const Foo &rhs)
{
*this = rhs;
}

//Assignment operator

void operator = (const Foo &rhs)
{
m_num = rhs.m_num;
}

private :
int m_num;
};

...
std::vector <Foo> myVector;

//Make enough room (not strictly necessary)

myVector.reserve (15);

//Add 15 objects

for (int i = 0; i < 15; i++)
{
//Create new object

Foo temp (i);

//Add a copy into the vector

myVector.push_back (temp);
}
...





[edited by - Kippesoep on June 4, 2003 10:53:54 AM]

Share this post


Link to post
Share on other sites
b.push_back(building("building name", 5));

is more compact and efficient than

b.resize(1)
b[0] = building("building name", 5);

Share this post


Link to post
Share on other sites
Read the post more closely, guys. This is an apvector, used for the Advanced Placement tests. There is no push_back.

Now, you say you get a compile error? What''s the exact error, and on what line is it? Try initializing your array to at least a single element.

Share this post


Link to post
Share on other sites

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!