C++:用 const 成员替换类数组的元素

标签 c++ arrays constants

我正在尝试修改具有 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 但仍以所需方式更改数组的解决方案。

最佳答案

数组与它无关。

Foo a, b;
a = b;

也应该无法编译,因为编译器不知道如何分配给 const 的值。

关于C++:用 const 成员替换类数组的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19186783/

相关文章:

c++ - 我的重复检查代码中的错误到底在哪里?

c++ - 如何在 lambda 捕获中显式捕获宏?

c++ - 如何在 cvCvColor 之后获取对 YUV 组件的引用?

c++ - 返回多个数组的函数

c++ - 返回常量 char 指针会产生错误

c++ - 在 vim 中查找 c++ 文档

c - 将可变长度二维数组传递给函数

ios - 如何快速在主数组中添加子数组

python - 为什么 True 和 False 在 Python 2 中仍然可以修改?

generics - 如何使用 Float 特性访问数字常量?