简体   繁体   中英

Assignment operator with a constant class member

I have a class called RSArray which contains a constant data member. But for this class I want to create a custom assignment operator. 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.

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 . Assignment by definition mutates the target.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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