-
vectors and objects
hi...i have a class that i made called Apartment. i need to create a vector and call the class objects. i'm trying to see how to do it but my book and a lot of websites barely have any info. i have objects inside the Apartment class: dispInfo and getName.
so far i'm declaring the vector like this:
Code:
vector<int> vector_one;
vector<Apartment> apt;
int user_input;
for(i=0; i<user_input; i++)
apt.push_back(i);
which does not work. however when i use
Code:
vector_one.push_back(i);
which runs fine.
how can i get apt to work like how vector_one works. also, how can i call the objects inside apt?
thanks
-
You need to call the Apartment constructor to create an Apartment object and push it onto the vector. Without seeing your code for the Apartment class, I could only guess you would be trying to do something like:
Code:
vector<Apartment> apt;
int user_input;
for(i=0; i<user_input; i++)
apt.push_back(Apartment());
Of course that would only work if your Apartment class had an appropriate default constructor.
Code:
vector_one.push_back(i);
That works because vector_one is a vector<int> and you are pushing ints onto that vector.
That does not work because you are pushing an int onto a vector that expects Apartment objects. Note: Actually that could work if you had a constructor that accepted an int as an argument during construction as a conversion would be made from apt.push_back(i) into apt.push_back(Apartment(i)) so you should be careful. I.e.:
Code:
class Test
{
public:
int data;
Test(int val=0) : data(val) {}
};
...
vector<Test> testVect;
...
testVect.push_back(Test()); // Pushes a Test object with data=0 onto vector
testVect.push_back(Test(2)); // Pushes a Test object with data=2 onto vector
testVect.push_back(4); // Pushes a Test object with data=4 onto vector
To avoid accidentally doing that you must use the keyword 'explicit', i.e.
Code:
class Test
{
public:
int data;
explicit Test(int val=0) : data(val) {}
};
...
testVect.push_back(4); // Error attempting to implicitly convert 4 into Test(4)
-
thanks.
Code:
one.push_back(Apartment());
calls up the default constructor. how can i call the set member functions (or methods) inside the class apartment?
-
After it has been constructed and pushed onto the vector?
Code:
class Person
{
string fname, lname;
int age;
public:
Person() {}
void SetAge( int _age ) { age = _age; }
void SetFirstName( string first ) { fname = first; }
void SetLastName( string last ) { lname = last; }
int GetAge() const { return age; }
string GetFirstName() const { return fname; }
string GetLastName() const { return lname; }
};
vector<Person> person;
// Push a Person object onto the vector
person.push_back(Person);
// Call the member functions for that object on the vector
person[0].SetFirstName(string("John"));
person[0].SetLastName(string("Doe"));
person[0].SetAge(28);
cout << "Name: " << person[0].GetFirstName() << ' ' << person[0].GetLastName()
<< " Age: " << person[0].GetAge() << endl;