Trying to compile the code below in Visual Studio 2010 gives me two errors about an unresolved external symbol. I’m pretty sure the issue is because I am using a function within a function but I don’t know specifically what I am doing incorrectly. The code looks ok to me.
#include <iostream>
using namespace std;
class fraction
{
public:
int gcd(int, int);
void simplifyfraction();
private:
int integral, numerator, denominator;
};
int main(){
return 0;
}
int gcd(int numerator, int denominator)
{
if (denominator > numerator)
return gcd(denominator, numerator);
if (numerator == denominator)
return numerator;
if (numerator%denominator == 0)
return denominator;
return gcd(numerator, numerator-denominator);
}
void fraction::simplifyfraction()
{
int mygcd;
mygcd = gcd(numerator, denominator);
numerator = numerator/mygcd;
denominator = denominator/mygcd;
}
The definition of
gcd()is not qualified with the class name and is treated as a free standing function, a different function from the member functiongcd()declared in thefractionclass.As
gcd()is invoked fromfraction::simplifyfraction()the compiler searches for a function namedgcd()and the first it finds is declared in the same scope assimplifyfraction(), namelyfraction::gcd()which has no definition (it does not find the fully defined freestandinggcd()function). The linker subsequently complains that it has an unresolved symbol.To correct change to:
Just to note this could also have been fixed by not having
gcd()as a member function (it does not access any member variables offraction, all variables are passed as arguments) or the invocation ofgcd()infraction::simplifyfraction()could be changed to: