Expand|Select|Wrap|Line Numbers
- #include <iostream>
- #include <vector>
- class Thing {
- private:
- int value;
- friend class Person;
- public:
- int getValue() { return value; }
- void setValue(const int val) { value=val; }
- Thing (const int val) { value=val; } // Constructor
- };
- class Person {
- private:
- std::vector<Thing> things; // All of Person's Things are stored in a vector
- public:
- void addThing(const int value) { things.push_back(Thing(value)); } // Adds Things to vector
- Thing getThing(const int i) { return things[i]; }
- int getThingValue(const int i) { return things[i].getValue(); } // Get and set value via Thing member function call
- void setThingValue(const int i, const int value) { things[i].setValue(value); }
- int getThingValueFriend(const int i) { return things[i].value; } // Get and set value via friendship from Thing
- void setThingValueFriend(const int i, const int value) { things[i].value = value; }
- };
- int main(int argc, char* argv[]) {
- Person* p = new Person();
- p->addThing(123);
- Thing temp = p->getThing(0);
- std::cout << temp.getValue() << std::endl; // #1: This works
- std::cout << p->getThingValue(0) << std::endl; // #2: As do these two
- std::cout << p->getThingValueFriend(0) << std::endl; // #3: ...
- std::cout << p->things[0].getValue(); // #4: But this doesn't
- delete p;
- return EXIT_SUCCESS;
- }
While I realize the "orthodox" way of getting a Person's Thing's value would be #2 or #3, method #4 perplexes me. My compiler (MinGW/gcc 3.4.2) gives this error message:
16 `std::vector<Thing, std::allocator<Thing> > Person::things' is private
33 within this context
I can't figure out how to make expressions like p->things[0].getValue() work, nor why they won't work. I suspect it's because of the expression being evaluated in main's namespace or something, since declaring Person and Thing each other's friends doesn't seem to affect the error at all, but I'm not really sure.
Anyway, while I can (and will) use a better approach to accessing Thing's value, I'd appreciate it if someone could explain to me why method #4 doesn't work, and tell me the simple correction to be made that will leave me banging my head against the desk for not getting it. Thanks.