Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have an int member named size within my blob class whose value I am attempting to change within a method. Initially, I tried...

void blob::make_union(blob parent_blob){
    parent=&parent_blob;
    parent_blob.size = parent_size
}

Then I tried making a function whose sole purpose was to change the size value. Its worth noting that it changes the values within the function as verified by some cout statements.

int blob::change_size(int dat_size){
    size=size+dat_size;
    return this.size;
}

after making the new method change my other method

'void blob::make_union(blob parent_blob){
    parent=&parent_blob;
    int temp = size;
    parent_blob.size = parent_blob.change_size(temp);
}'

still no dice. The following within main function does work.

if (charmatrix[m-1][n-1]==charmatrix[m][n]){ blobmatrix[m][n].make_union(blobmatrix[m-1][n-1]); blobmatrix[m-1][n-1].size=blobmatrix[m-1][n-1].size + blobmatrix[m][n].size;

What am I doing wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
257 views
Welcome To Ask or Share your Answers For Others

1 Answer

You are passing your blob class by value: you are making a copy of your blob object, and that is what the function change_size is working with.

void increment_number(int i) { ++i; }
void increment_number_ref(int& i) { ++i; }

int main()
{
    int n = 6;
    // This takes a copy of the number, and increments that number, not the one passed in!
    increment_number(n);
    // n == 6
    // This passed our object by reference. No copy is made, so the function works with the correct object.
    increment_number_ref(n);
    // n == 7
    return 0;
}

You need to pass your blob by reference (or as a pointer) if you wish to modify that object's value: see above.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...