重载赋值运算符带下标运算符 [英] overloading assignment operator With subscript operator

查看:151
本文介绍了重载赋值运算符带下标运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我重载了下标运算符和赋值运算符,我试图获得正确的值赋值运算符
示例
Array x;
x [0] = 5;

通过重载下标运算符i可以获得值0,但是当我重载赋值运算符它做赋值,但它不使用我的重载函数,因为vaiable 2的值应为5.

I overloaded both subscript operator and assignment operator and I am trying to get right value to assignment operator example Array x; x[0]=5; by overloading subscript operator i can get value 0 but when i overload assignment operator it does the assignment but it doesn't use my overloaded function because vaiable 2 should have value 5.

class Array
{

public:
    int *ptr;
    int one,two;
    Array(int arr[])
    {
        ptr=arr;
    }

    int &operator[](int index)
    {
        one=index;
        return ptr[index];
    }
    int & operator=(int x){
        two=x;
        return x;
    }   
};

int main(void)
{
    int y[]={1,2,3,4};
    Array x(y);
    x[1]=5;
    cout<<x[0]<<endl;
}


推荐答案

code> operator = ,因为您没有分配给 Array 的实例,而是分配给 int 。这将调用您的运算符:

It does not use your operator= because you are not assigning to an instance of Array, you're assigning to an int. This would invoke your operator:

Array x;
x = 7;

如果你想拦截到 operator [] 返回,您必须返回一个代理对象并为该代理定义赋值运算符。示例:

If you want to intercept assignments to what operator[] returns, you must have it return a proxy object and define the assignment operator for that proxy. Example:

class Array
{
  class Proxy
  {
    Array &a;
    int idx;
  public:
     Proxy(Array &a, int idx) : a(a), idx(idx) {}
     int& operator= (int x) { a.two = x; a.ptr[idx] = x; return a.ptr[idx]; }
  };

  Proxy operator[] (int index) { return Proxy(*this, index); }
};

这篇关于重载赋值运算符带下标运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆