I should get this by now, but I'm just not getting it yet. The trouble is operator='s argument could be non-const, but that breaks std::vector::push_back because it makes the item const, so operator= has to accept a const object. Well, I'm not certain on how I'm supposed to modify the this object working like this.
#include <vector>
#include <map>
#include <iostream>
using namespace std;
int font[] = {0, 31, 0, 31, 0, 31, 0, 31};
class Foo {
int size_;
std::map<int, int> chars_;
public:
Foo(int *font, int size);
unsigned int Size() const { return size_; }
void Add(int ch);
bool operator==(const Foo &rhv) const;
int &operator[](int i);
int const operator[](int i);
Foo operator=(const Foo &rhv);
};
Foo::Foo(int *font, int size) {
for(int i = 0; i < size; i++ ) {
chars_[size_++] = font[i];
}
}
bool Foo::operator==(const Foo &rhv) const {
if(Size() != rhv.Size()) return false;
/*for(int i = 0; i < Size(); i++ ) {
if ( chars_[i] != *rhv[i] )
return false;
}*/
return true;
}
int &Foo::operator[](int i) {
return chars_[i];
}
int const Foo::operator[](int i) {
return chars_[i];
}
Foo Foo::operator=(const Foo &rhv) {
if( this == &rhv ) return *this;
for(unsigned int i = 0; i < rhv.Size(); i++ ) {
//Add(*rhv[i]);
//chars_[size_++] = rhv[i];
}
return *this;
}
void Foo::Add(int ch) {
chars_[size_++] = ch;
}
int main()
{
vector<Foo> baz;
Foo bar = Foo(font, 8);
baz.push_back(bar);
}
Edit: Well, I've spent some time reading about const again. Is what I want to do even possible? The reason I ask is because of this sentence: If it doesn't compile without const qualifier and you are returning a reference or pointer to something that might be part of the object, then you have a bad design.
I took that into account, and refrained from returning a reference in the const method. That yielded this error:
test.cpp:18: error: 'const int Foo::operator[](int)' cannot be overloaded
test.cpp:17: error: with 'int& Foo::operator[](int)'
test.cpp:41: error: prototype for 'const int Foo::operator[](int)' does not match any in class 'Foo'
test.cpp:37: error: candidate is: int& Foo::operator[](int)
Getting rid of the int & Foo::operator[] gets rid of that error. I know I can just make a new accessor to apply changes to chars_, but I thought I'd update this and find out if what I'm trying to do is possible at all.