简体   繁体   中英

Square bracket overloading operator to set instead of get c++

For getting the value(ie the function returns the value)

for ex -

if we do this in main.cpp

cout << Object[0] << endl;

it will print the first element of the object array.

and the function will look like this

double myArray::operator[](int index) const {

    *//your code*
}

but what if we need to set the value what would be the prototype going to look like?

Let's say in main.cpp, we have

object[0] = 5;

Now this should set the first element as 5 we know that it shouldn't return anything!! so return_type is void!! but how we going to pass the index(ie 0) and the RHS(Right hand side) value into the function?

Just declare two operators

const double & myArray::operator[](int index) const {

    *//your code*
}

and

double & myArray::operator[](int index)  {

    *//your code*
}

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