April 20, 201016 yr I'm making a simple C++ program to roll characters for a strange little game me and my friends have picked up called "Maid". Frankly in the past it has taken hours to roll the characters manually and I'd like to automate it. I could probably accomplish this in a much easier way but I'd like to take this opportunity to practice with classes, operator overloading, polymorphism and all that good stuff. The problem is in my attribute table class where I'm trying to overload the [] operator to return a reference to a member of the table it contains such that I can use it as an lvalue. Here's the code for the attribute table class: class attributeTable : public baseAttribute { public: attributeTable(int size) : table(size) {}; baseAttribute*& operator[](size_t index) { return table[index]; }; virtual string get() const { return table[rng(0, table.size() -1)]->get(); }; private: vector< baseAttribute* > table; }; The purpose of the attributes themselves and the attribute tables deriving from the base attribute class is such that tables can contain other tables, ie if I roll onto another table instead of an attribute, that table will roll and return the string up the line. So this class contains a vector of pointers to objects of the abstract base class, and I'd like the [] operator to return a reference to one of these pointers so I can use attributeTable[0] as an lvalue in attributeTable[0] = &attribute for example instead of simply making the vector public and doing attributeTable.table[0] = &attribute or something like that. The only problem is that when I try to compile with the overloaded [] operator I get this message: In copy constructor `std::basic_ios<char, std::char_traits<char> >::basic_ios(const std::basic_ios<char, std::char_traits<char> >&)': `std::ios_base::ios_base(const std::ios_base&)' is private within this context What am I doing wrong here?
April 20, 201016 yr Author Oh wait... never mind... it was something completely different causing the error. The [ ] actually works fine... it's the output stream operator it was having a problem with. Anyone know the answer to THAT one? ostream& operator<<(ostream output, const attributeTable &outputTable){ output << outputTable.get(); return output; }
April 22, 201016 yr friend ostream& operator<<(ostream output, const attributeTable &outputTable){ output << outputTable.get(); return output; } You need the 'friend' attribute. You can also shorten the code to this: friend ostream& operator<<(ostream output, const attributeTable &outputTable){ return output << outputTable.get(); } Since the << operator returns *this. Edit: You should also pass `output' as a reference rather than by value as it is now.
April 24, 201016 yr Author Ah, oops, silly me, returning a reference to ostream when the input is by value... thanks for that. Friend in this case was actually unnecessary, as .get() is a public member of attributeTable.
Create an account or sign in to comment