简体   繁体   English

具有常数 class 成员的赋值运算符

[英]Assignment operator with a constant class member

I have a class called RSArray which contains a constant data member.我有一个名为 RSArray 的 class ,其中包含一个常量数据成员。 But for this class I want to create a custom assignment operator.但是对于这个 class 我想创建一个自定义赋值运算符。 See code below: -请参阅下面的代码: -

class RSArray
{
private:
    int *data;
    const int max_size;
public:
    RSArray(size) : max_size(size)
    {
        data = new int[max_size];
    }
    RSArray &operator=(const RSArray &src)
    {
         data = new int[src.max_size];
         max_size = src.max_size
    }

}

int main()
{
    RSArray one(10), two(15);
    one = two;
}

The above code giving me error when assignment operator is called because we can't change value of a const data member.上面的代码在调用赋值运算符时给了我错误,因为我们无法更改 const 数据成员的值。

Is there any other way to get rid of this error?有没有其他方法可以摆脱这个错误?

Is there any other way to get rid of this error?有没有其他方法可以摆脱这个错误?

Yes, remove the const from max_size .是的,从max_size中删除const Assignment by definition mutates the target.根据定义赋值会改变目标。

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

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