How to pass a function that returns some value from one class as a variable in a function defined in another class. At the moment my code looks like this:

float A::decay(){ B b; float N; const int HL=946; const int G=126; float T; if(b.min()>0){ T=(float)(b.min()-G)/HL; N=pow(2,-T); } return N; } int B::min(){ int min=dtim[0][0][0]; for(int i=0;i<N;i++){ for(int j=0; j<K; j++){ for(int q=0; q<L; q++){ if (dtime[i][j][q] < min)min = dtime[i][j][q]; } } } return min; } 

When trying to call the min () function in decay (), min is always zero.

  • do you know what a pointer to a function is? - ampawd
  • @ampawd would not refuse to explain by the example of this code - robado

2 answers 2

According to the sign, obviously.

But it is easier to pass a pointer to the class, and from there call the desired method.

 float A::decay(B * b){ // B b; - это больше не нужно ... здесь без изменений if (b->min()>0){ .... 

    You have a problem in calculating min , rather than in the transfer function. Rather, not in the transfer , and the call . You are not doing anything supernatural ... The code below is a simplified version of yours. But what is your dtim , what values ​​are there, etc. etc. - we don't know the same! Then, in you in decay an object B is created by the default constructor - is that necessary? Maybe in this b all dtim elements are null?

    Another thing is if you really need to pass a member function of one class to another ...

     class B { public: B(int x):x(x){} void out() { cout << "b = " << x << endl; } private: int x; }; class A { public: void func(int x) { B b(x); b.out(); } }; int main(int argc, const char * argv[]) { A a; a.func(5); } 
    • the second option, the calculated values ​​of min are correct, when calling a print from class B - robado
    • @robado You know, give me some minimal self-sufficient example - ru.stackoverflow.com/help/mcve - Harry