Try modifying the part you add the nodes like this and see if it works.
1 2 3 4 5 6 7 8 9 10 11
|
for(int j=0;j<REQ_NUM;j++)
{
rand_num=(rand()%num_stream) + 1;
g.add_stream_requested(rand_num);
temp=((rand_num-1)/4) +1;
node_source=nodes.at(temp-1);
stream & s=node_source.find_stream(rand_num); //<- here add '&' between 'stream' and 's'
s.add_requested_nodes(g.getnodeId());
}
|
You see, what
stream s=node_source.find_stream(rand_num);
does is that it finds the stream you want to modify and the create a new stream object, s, and then copy the stream you want to modify to s. Consequently, no matter what you do to s, the object you want to modify won't be affected...
However, if you declare s like
stream & s=node_source.find_stream(rand_num);
(that is you declare s as a 'reference' to the object returned by
node_source.find_stream(rand_num);
), what you effectively do is say to your compiler: "I want s to be a nickname for the object returned from
node_source.find_stream(rand_num);
, so that whatever changes I do to s actually modify that object".
But, there's one more thing you have to check.
node_source.find_stream(rand_num);
must also return a reference to the desired object. Consider the following... I want you to notice that
you can only modify a variable when there is a 'reference chain' from the target variable all the way to the variable you use for the modification.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
|
#include <iostream>
using namespace std;
class MyClassRef
{
public:
MyClassRef(int v){value=v;}
int & getValue() {return value;} //notice the '&' here
private:
int value;
};
class MyClassVal
{
public:
MyClassVal(int v){value=v;}
int getValue() {return value;} //no '&' here
private:
int value;
};
int main()
{
MyClassRef mcr(5);
MyClassVal mcv(10);
cout << "MyClassVal" << endl;
cout << mcv.getValue() << endl;
//trying to modify...
int var_val=mcv.getValue();
var_val=123;
cout << mcv.getValue() << endl;
//nope... neither var_val is a reference nor getValue() returns a reference...
//trying to modify...
int & var_ref0=mcv.getValue();
var_ref0=123;
cout << mcv.getValue() << endl;
//nope... var_ref0 is a reference but getValue() does not return a reference...
cout << "MyClassRef" << endl;
cout << mcr.getValue() << endl;
//trying to modify...
var_val=mcr.getValue();
var_val=123;
cout << mcr.getValue() << endl;
//nope... because even though getValue() returns a reference, var_val isn't a reference
//trying to modify...
int & var_ref1=mcr.getValue();
var_ref1=123;
cout << mcr.getValue() << endl;
//yeap! getValue() returns a reference and var_ref1 is a reference
cout << "hit enter to quit..." << endl;
cin.get();
return 0;
}
|