I am trying to define a class named RationalNumber
. In the constructor I want to simplify the fraction represented by the RationalNumber
using a callback function to another function (named simplification
), but I receive some errors and I can't figure out what I am missing.
The first error is cannot convert from 'void (__cdecl *)(RationalNumber &)' to 'RationalNumber::pointer_to_f' Prob2 ...\source\repos\Prob2\Prob2\NumarRational.h 21
#pragma once
#include <iostream>
using namespace std;
class RationalNumber {
typedef void (RationalNumber::*pointer_to_f)(RationalNumber&);
private:
int a;
int b;
void callback(pointer_to_f);
static int gcd(int, int);
public:
RationalNumber(int = 0, int = 0);
static void simplification(RationalNumber&);
};
RationalNumber::RationalNumber(int x, int y) {
this->a = x;
this->b = y;
pointer_to_f p = &simplification; // <-- line 21, location of the first error
callback((p)(this));
}
int RationalNumber::gcd(int a, int b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
void RationalNumber::simplification(RationalNumber& x) {
int d = gcd(x.a, x.b);
if (d != 1) {
x.a /= d;
x.b /= d;
}
}
void RationalNumber::callback(pointer_to_f *p(RationalNumber& x) ) {
(*p)(x);
}
The full error log:
Error C2440 'initializing': cannot convert from 'void (__cdecl *)(RationalNumber &)' to 'RationalNumber::pointer_to_f' Prob2 ...\source\repos\Prob2\Prob2\NumarRational.h 21
Error C2511 'void RationalNumber::callback(RationalNumber::pointer_to_f *(__cdecl *)(RationalNumber &))': overloaded member function not found in 'RationalNumber' Prob2 ...\source\repos\Prob2\Prob2\NumarRational.h 39
Error C2065 'x': undeclared identifier Prob2 ...\source\repos\Prob2\Prob2\NumarRational.h 40
Error (active) E0144 a value of type "void (*)(RationalNumber &x)" cannot be used to initialize an entity of type "RationalNumber::pointer_to_f" Prob2 ...\source\repos\Prob2\Prob2\NumarRational.h 21
Error (active) E0147 declaration is incompatible with "void RationalNumber::callback(RationalNumber::pointer_to_f)" (declared at line 11 of "...\source\repos\Prob2\Prob2\NumarRational.h") Prob2 ...\source\repos\Prob2\Prob2\NumarRational.h 39
Error (active) E0109 expression preceding parentheses of apparent call must have (pointer-to-) function type Prob2 ...\source\repos\Prob2\Prob2\NumarRational.h 22
Error (active) E0020 identifier "x" is undefined Prob2 ...\source\repos\Prob2\Prob2\NumarRational.h 40
Error C2064 term does not evaluate to a function taking 1 arguments Prob2 ....source\repos\Prob2\Prob2\NumarRational.h 22
Thank you!