我正在尝试修改具有 const 成员的对象数组:
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;
}
但编译器不会让我:
$ 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
我确信编译器有其原因,我很想知道为什么代码不能正常工作。
而且我也想知道如何对f
数组进行预期的更改。
现在,以下内容为我完成了这项工作,但它看起来很错误:
#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;
}
我很欣赏一个不涉及memcpy
但仍以所需方式更改数组的解决方案。