繁体   English   中英

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

[英]C++: Replace elements of an array of a class with const members

我正在尝试修改具有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值。

您不能更改const成员的值。 但是f[0] = Foo(Quux,3); 除了f[0].a_ = Quux; f[0].b_ = 3; f[0].a_ = Quux; f[0].b_ = 3; 并且由于它们都是const成员,因此无法编译。

您在这里唯一可以做的就是使用指针,例如:

#include <memory>

int main(int argc, char* argv[]) {
    // ...
    std::unique_ptr<Foo> f[] = {
        std::unique_ptr<Foo>(new Foo(Baz, 42)),
        std::unique_ptr<Foo>(new Foo(Qux, 32))
    };

    f[0].reset(new Foo(Quux, 4));
}

如果使用gcc,则必须使用-std = cpp11标志。 在头“内存”中定义unique_ptr

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM