I'm trying to modify an array of objects which have const members:
enum Bar {
Baz,
Qux,
Quux
};
class Foo {
public:
Foo(Bar a, int b): a_(a), b_(b) {};
private:
const Bar a_;
const int b_;
};
int main(int argc, char* argv[]) {
Bar b[] = {
Baz,
Baz
};
// This works fine
b[0] = Qux;
Foo f[] = {
Foo(Baz,42),
Foo(Qux,32)
};
// This doesn't
f[0] = Foo(Quux,3);
return 0;
}
But the compiler wouldn't let me:
$ make test
g++ test.cc -o test
test.cc: In member function ‘Foo& Foo::operator=(const Foo&)’:
test.cc:7:7: error: non-static const member ‘const Bar Foo::a_’, can’t use default assignment operator
test.cc:7:7: error: non-static const member ‘const int Foo::b_’, can’t use default assignment operator
test.cc: In function ‘int main(int, char**)’:
test.cc:31:22: note: synthesised method ‘Foo& Foo::operator=(const Foo&)’ first required here
make: *** [test] Error 1
I'm sure the compiler has its reasons and I'm eager to learn why the code is not meant to work.
And I do also want to know how to make the intended changes to the f array.
Right now, the following does the job for me, but it looks so wrong:
#include <cstring>
#include <iostream>
enum Bar {
Baz,
Qux,
Quux
};
class Foo {
public:
Foo(Bar a, int b): a_(a), b_(b) {};
/*Foo &operator=(Foo const& f) {
return f;
}*/
const Bar a_;
const int b_;
};
int main(int argc, char* argv[]) {
Bar b[] = {
Baz,
Baz
};
// This works fine
b[0] = Qux;
Foo f[] = {
Foo(Baz,42),
Foo(Qux,32)
};
// This doesn't
//f[0] = Foo(Quux,3);
// This does...
Foo foo1(Quux, 344);
memcpy(&f[0], &foo1, sizeof(foo1));
std::cout << "Hi " << f[0].b_ <<"\n";
return 0;
}
I'd appreciate a solution that doesn't involve memcpy but still changes the array in the desired way.
Foo a, b; a = b;should also fail to compile, as the compiler does not know how to assign to a value which isconst.farray. Just like it's done in the array ofBars.