Oct 14, 2015 at 6:55am UTC
I am in a pickle. I keep getting an undefined reference error in any member function or friend that calls the constructor.
This is snippet of the errors I am getting from one of my member functions:
g++ -pedantic RationalMain.o Rational.o -o main
Rational.o: In function `Rational::operator+(long long) const':
Rational.cpp:(.text+0x2da): undefined reference to `Rational::Rational(long long, long long)'
A snippet from my header file
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#ifndef _RATIONAL_H_TJD_
#define _RATIONAL_H_TJD_
#include <iostream>
using namespace std;
class Rational
{
long long _p;
long long _q;
public :
Rational();
Rational(long long P, long long Q = 1);
Rational (const Rational&);
Rational operator + (long long ) const ;
};
#endif
A snippet of the member function in my .cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
#include "Rational.h"
#include <iostream>
#include <cstdlib>
using namespace std;
Rational :: Rational()
{
}
Rational :: Rational(const Rational& r)
:_p(r._p) , _q(r._q)
{}
Rational Rational::operator + (long long LLr) const
{
return *this + Rational (LLr); //I believe the error is happening here when using 'Rational (LLr)
}
My makefile
1 2 3 4 5 6 7 8 9
main :: RationalMain.o Rational.o
g++ -pedantic RationalMain.o Rational.o -o main
RationalMain.o: RationalMain.cpp Rational.cpp Rational.h
g++ -Wall -pedantic RationalMain.cpp -c
Rational.o: Rational.cpp Rational.h
g++ -Wall -pedantic Rational.cpp -c
clean:
-rm *.o
Last edited on Oct 14, 2015 at 6:56am UTC
Oct 14, 2015 at 7:02am UTC
From what you have given us, it looks like you haven't defined the overloaded constructor that takes in long long integers as arguments. You declared it in the header file but there is no implementation for it.
Oct 14, 2015 at 1:04pm UTC
Hi,
Some unrelated things:
64 bit systems sometimes complain (mine does) about long long
types because long is already 64 bit.
You should compile with -Wall -Wextra -pedantic
as a minimum.
Avoid having using namespace std;
Google to see why, and what to do instead.
Your default constructor should still set the denominator to 1. Or just disallow it:
Rational() = delete ; // C++11
If you want default initialisation:
Rational() = default ; // C++11
So then you won't need a definition of that constructor, but the denominator will be zero - which isn't good.
Hope all goes well :+)
Last edited on Oct 14, 2015 at 1:06pm UTC
Oct 14, 2015 at 2:12pm UTC
you dont have a implement the constructor(long long,long long)
return a reference with the operator + .
add the member to this member then return *this.