On 2006-11-15 15:19, Oliver Bleckmann wrote:
Quote:
i want to create a object of class Hotel, which own a variable number of
objects
of the class Zimmer (~ rooms). accessed in main like this
Hotel hotel("name",9);
std::cout << hotel.zimmers[1]->getZimmerZahl(); //(~
hotel.rooms->getRoomNumber)
You need to make the Zimmer and the Hotel two separate objects, and then
make the Hotel contain a number of Zimmers, each of which has a zhal.
The best way to contain the Zimmers is to place them in an vector in Hotel:
#include <vector>
#include <iostream>
class Zimmer {
private:
int zahl;
public:
Zimmer(int z) : zahl(z) {}
int getZimmerZahl() const {
return zahl;
}
};
class Hotel {
public:
std::vector<Zimmerzimmers; // vector holding Zimemrs
Hotel(int nr) { // Create and init Zimmers
for (int i = 0; i < nr; ++i)
zimmers.push_back(Zimmer(i));
}
};
int main() {
Hotel hotel(5);
std::cout << hotel.zimmers[3].getZimmerZhal();
return 0;
}
It does not use the -operator to dereference a pointer but in most
cases this is better. If you really want to use pointers instead keep
the Zimmer as it is but use the following for Hotel:
class Hotel {
public:
std::vector<Zimmer*zimmers; // vector holding pointers to Zimmers
Hotel(int nr) { // Create and init Zimmers
for (int i = 0; i < nr; ++i)
zimmers.push_back(new Zimmer(i)); // use new
}
~Hotel() { // destructor, needed to clean up
for (int i = 0; i < zimmers.size(); ++i)
delete zimmers[i];
};
Then you need to use the -operator to access the Zimmer-members like
getZimmerZahl():
int main() {
Hotel hotel(5);
std::cout << hotel.zimmers[3]->getZimmerZhal();
return 0;
}