开发者

How to assign value to left side using Overload operator[]?

I have made the following code:-

class A{
     bool bFlag[2];
public:
  A(){
      for(int  i = 0; i < 2; i++)
          bFlag[i] = false;
  }

  bool operator[](int r){ //i know how to assign value to R.H.S using operator[]
      if( r >= 0 || r < 2 ){
          bFlag[r] = true;
          return bFlag[r];
   }
   return false;        
  }   
};

int main(){
    A obj;
开发者_运维技巧    bool x;
    x = obj[0]; //this i know
    //obj[1] = x; //how to do this is my doubt?
    return 0;
}

I dont know to set value to L.H.S using operator[]. Please guide me to how to set x value to obj[1]


To use [] as an lvalue your overloaded [] should return by reference.

Is it okay to return reference to a private member?
Yes, It is perfectly fine.
Most of the STL classes do that if you see the STL.
The rule is you should return a const reference to your private member if you do not wish the user to modify the contents there or if you want to allow users to modify it you can return a non const reference.

You basically hide(Abstract) the details of your class from the user of class by making them private, but you still provide the functionality to be able to modify individual elements.


Als is right, but here is an example:

class A{
private:
    int val[10];
public:
    A(){}
    int& operator[](int i) {
        return val[i];
    }
};

this makes in posible to do things like

A a;
a[2] = 2;

you should of course add the old method as well. to optimize for l-value to making it.

class A{
private:
    int val[10];
public:
    A(){}
    const int operator[](int i) const {
        return val[i];
    }
    int& operator[](int i) {
        return val[i];
    }
};
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜