|
-
April 5th, 2011, 04:45 AM
#3
Re: How to make a function change a variable
 Originally Posted by loves_oi
i have tried the second one and fixed some deficient point in your code. It should be correct.
I'm sure you have the best intentions, but posting bad solutions without any form of explanation is not helpful.
 Originally Posted by PlutoRocks
well.. you'll see, here is my problem:
Code:
class Knap
{
public:
void fillArrays(Knap);
int weight[99];
int value[99];
int W;
}
Please use code tags and properly indent your code to keep it readable.
Note that a class definition must be closed with a semicolon, you forgot that.
What's the reason for passing a Knap to the member function fillArrays? Since this is a normal member function, it already has access to an instance of Knap. In main you have to call the function on an instance of Knap, as in
Code:
myKnap.fillArrays(...);
The instance you called the member function on is available in the member function via the this pointer. The member variables of the Knap instance are even directly accessible. That is, you can write
Code:
void Knap::fillArrays()
{
this->weight[0] = 1;
// or just
weight[0] = 1;
}
This will change the value of the member variable weight that belongs to the instance on which you called the fillArrays member function.
What happens in your code is that the Knap argument passed to the function is passed by value, which means that a copy is made and the function works on the copy. Since you only changed values in this copy, the values in your Knap instance in main are not affected.
Cheers, D Drmmr
Please put [code][/code] tags around your code to preserve indentation and make it more readable.
As long as man ascribes to himself what is merely a posibility, he will not work for the attainment of it. - P. D. Ouspensky
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|