Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
264 views
in Technique[技术] by (71.8m points)

c++ - unable to change member value with method

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...