I'm a new user here so I hope I can format everything correctly and be clear. I'm on a Linux machine using gcc 12.2.0 with the -std=c++11 flag, I have 2 files that, among other classes, contain the following (some irrelevant code removed):
TwoDim.h
namespace Dim2 {
class Point {
private:
long x,y;
public:
explicit Point(long x=0, long y=0);
long GetX() const;
long GetY() const;
};
}
TwoDim.cpp
using namespace Dim2;
std::ostream& operator<<(std::ostream& os, const Point& pt){
os<<pt.GetX()<<"x "<<pt.GetY()<<"y";
return os;
}
Where I overloaded operator<<, however when I try to ouput the point's coordinates in my main.cpp file:
#include "TwoDim.h"
int main() {
Point test(1,2);
std::cout<<test;
}
the compiler gives me an undefined reference error despite me not having defined any other overload of operator<< (at least not in this namespace). As far as I can tell the function signature is correct so I'm really not sure what's going on here.
I've tried a number of things to solve this
Firstly I tried moving the overload inside TwoDim.h, outside the class
class Point {
private:
long x,y;
public:
explicit Point(long x=0, long y=0);
long GetX() const;
long GetY() const;
};
}
std::ostream& operator<<(std::ostream& os, const Point& pt){
os<<pt.GetX()<<"x "<<pt.GetY()<<"y";
return os;
}
then I tried leaving only the function prototype in TwoDim.h while keeping the implementation in TwoDim.cpp
//In TwoDim.h
class Point {
private:
long x,y;
public:
explicit Point(long x=0, long y=0);
long GetX() const;
long GetY() const;
};
}
//In TwoDim.cpp
std::ostream& operator<<(std::ostream& os, const Point& pt){
os<<pt.GetX()<<"x "<<pt.GetY()<<"y";
return os;
}
But the error persists in both attempts