C ++ operator []

I am trying to implement the [] operator, which should be used once for Set and once as Get, I need to distinguish between these two cases, as in the case of get, I need to throw an exception if the returned value is -1; whereas in the case of Set, I just overwrite the value. appple [2] = X; y = apple [2];

I do not know how to distinguish between two modes, my signature is a function:

   double& Security::operator[](QuarterType index){
    if(index<0 || index>MAX_QUATERS){
        throw ListExceptions::QuarterOutOfBound();
    }
    return evaluation[index].getValueAddress();
   }
+4
source share
6 answers

C ++ doesn't just let you distinguish between

appple[2] = X; 
y=apple[2];

The most common solution is to return a proxy object:

struct AppleProxy
{
   Security & obj; 
   unsigned index;

   AppleProxy(Security &, unsigned) : ... {}

   operator double()   // your getter
   {
      return obj.GetAt(index);
   }

   operator=(double rhs)
   {
      obj.SetAt(index, rhs);
   }
}

AppleProxy operator[](unsigned index) { return AppleProxy(*this, index); }

The proxy requires significant attention to detail, I have omitted constvalidity, life time management, take-the-address-of ( double & x = apple[2]; x = 17;), etc.

Because of the traps, I try to avoid them.

+3

, python #, ++ get set . , operator[], , , , , .

, ; , , , :

struct proxy
{
    operator double() const;
    void operator=(double x);
};

- , , , get. , - -, , .

( , , , Security)

; double double& , , , auto. - , double&!

, - , operator[], , double. , , :

  • , Security double, get set. (, , , - )
  • get set. , , - , .
  • API , - operator[], , , operator[] / double.
+6

[], Set Get

. ( ), .

set get .

+4

- [], operator double operator =. , -1, , , .

+1

"Get" const const:

const double& Security::operator[](QuarterType index) const

"Set" , :

double& Security::operator[](QuarterType index)

, const, const_cast const. ( : const -ness undefined, const).

. , get set. - QuarterType: , , QuarterType . , , , .

( QuarterType - , const QuarterType&, .)

-2
source

See operator overloading at cppreference.com. The Mass Index line explains what you need exactly:

User classes that provide access to an array that allows reading and writing usually define two overloads for operator[]: const and non-const options:

struct T {
          value_t& operator[](std::size_t idx)       { return mVector[idx]; };
    const value_t& operator[](std::size_t idx) const { return mVector[idx]; };
};

If the value type is known as a built-in type, the const variant must be returned by value.

(continued)

So you should define double Security::operator[](QuarterType index) constinstead const double& Security::operator[](QuarterType index) const.

-2
source

All Articles