There are a number of problems here. First, you can't declare
MY_OBJECT* objects[] inside a class. This is an array of indeterminate size, so C++ can't know how large the type MY_ROOM is. There is a trick that allows you to put this as the last member variable of the class, but you don't want this right now. What you really want is a std::vector.
Your type names are strange. Just call them Room and Object.
Next, your operator>> usage is backwards. When used in the cout style, this operator means "put to" or "take from." What
bedroom >> wall means in this idiom is "take something from bedroom and put it in wall." Instead, you want
bedroom << wall, or "take wall and put it in bedroom, so just switch that operator around. Oh, and don't use __variables like that, there's no point and it just adds noise to the function. And one more thing, if it needs to be able to access member variables, it should be a member function.
But now onto the meat of your function. Firstly, even if you had an empty array as you tried to declare, it's empty. There is no memory allocated for it. You can't just grow an array like that and you're trying to dynamically grow an array by assigning to it. This will overwrite adjacent data and/or crash your program. However, if you use std::vector, all you need to do is call push_back.
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
|
#include <iostream>
#include <vector>
class Object {
public:
int x, y, w, h;
};
class Room {
std::vector<Object*> objects;
public:
Room& operator<<(Object &object) {
objects.push_back(&object);
return *this;
}
auto num_objects() {
return objects.size();
}
};
int main() {
Object door, roof, wall, floor, desk;
Room bedroom;
std::cout << bedroom.num_objects() << std::endl;
bedroom << door << roof << wall << floor << desk;
std::cout << bedroom.num_objects() << std::endl;
return 0;
}
|