简体   繁体   中英

Changing the value of a member vector variable in a member function

A have a function in my class that looks something like this:

void SomeClass::SomeFunction(int i, int j){

    float var = MemberVector[i][j];
    float temp;
    temp = var * -1;
 ~~~Some Condition~~~{
        MemberVector[i][j] = temp;
    }
}

I want to get the value at [i][j] in the vector member variable, and multiply it by -1, ie make it positive if it is negative and vice verse.

I thought that the vector operator[] returns a reference to the value a the position specified inside the square brackets, but when I run my code it isn't change the values in the member vector variable.

Is there a way to refer to get value at [i][j] in the member variable by reference inside a member function and change it as I describe?

If you write something like

int x = y;

then x is a copy of y . Changing x will not change y .

To do that, you need a reference, like this

int &x = y;
x = 42; // now y is also 42

In your case, you don't even really need a reference. You could just modify the element directly,

MemberVector[i][j] *= -1;

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