Home > Mobile >  correct usage of reference in a class
correct usage of reference in a class

Time:04-25

Here is my usage:

void fun_out(int& mkol){
  mkol = 3;
}

class refTest{


public:
  int pol_as;

  refTest(int& poul):
    pol_as(poul){}

  void fun1(){
    fun_out(pol_as);
  }
};

int main(){

     int asl = 46;
     refTest testcase(asl);     // testcase.pol_as = 46

     testcase.fun1();           // testcase.pol_as = 3
     printf("testcase.pol_as: %d\n", testcase.pol_as);


}

I need to change asl to the value in fun_out, i.e. 3 in this case; however, this code cannot do it. Only testcase.pol_as is modified from 46 to 3. Do we have a method that can change the int(asl) or a pointer value(int* asl_ptr) outside a class w.r.t. the result of a function (fun1) within this class?

CodePudding user response:

I need to change asl to the value in fun_out

Currently you're storing a copy of asl into the data member pol_as. This means that when you call fun_out from inside fun1 it will only effect that copy. So to achieve the desired effect you can either make the data member pol_as as an lvalue reference to int or you can directly call fun_out passing asl as shown below:

Method 1

class refTest{

private:
//----v---------->lvalue reference 
  int &pol_as;
public:
  refTest(int& poul):
    pol_as(poul){}

  void fun1(){
    fun_out(pol_as);
  }
};

Demo

Method 2

Or directly call fun_out passing asl.

int main(){

     int asl = 46;
     
     fun_out(asl);//directly pass asl
     std::cout<<"asl: "<<asl;

}

Demo

CodePudding user response:

You're trying to store a reference in normal data variable. You need to make pol_as a reference than your code will run fine.

  • Related