I'm trying to overload the << operator for a class (easy, right? :P)
However, I get the linker error: undefined reference to `operator<<(std::ostream&, particle const&)'

Which my understanding means the compiler can't find the implementation for operator<<.

I'm not sure whats going on here, since I've already implemented the function. Previously when I've overloaded << for a class I'd define it as a non-friend and use x.getvariable(), but I can't figure out why this won't work.

//Inside particle.h

#include <sstream>

class particle {
     private:
          double Xcomp;
          double Ycomp;
          double Zcomp;
     public:
          ...
          friend std::ostream& operator<<(std::ostream& outs, const particle& x);
     };

//Inside particle.cpp

#include <sstream>
#include "particle.h"
using namespace std;

ostream& operator<<(ostream& outs, const particle& x){
     outs << Xcomp << " " 
             << Ycomp << " " 
             << Zcomp << " ";
     return(outs);
}

//in main

#include "particle.h"

void main() {
     particle x;
     cout << x;
}

im not seeing a #include <iostream> anywhere.

At first glance, your stuff looks good...

Have you tried #include<iostream> ??

#include <ostream> instead of #include <sstream> in particle.h and/or particle.cpp .

ostream& operator<<(ostream& outs, const particle& x){
     outs << x.Xcomp << " " 
             << x.Ycomp << " " 
             << x.Zcomp << " ";
     return(outs);
}
#include "particle.h"
#include <iostream>
using std::cout;

int main() {
     particle x;
     cout << x;
}

Hi,

I've #include <iostream> for particle.cpp, and particle.h and iostream was already included in main, but this still doesn't resolve the linker error.

just a side note in dev c++, in the class browser, the function appears by itself as operator<(ostream ... ) when implemented as above, but changing the prototype and implementation to operator <<(ostream ... ) makes it appear correctly in the browser. Doesn't really make a difference either way in the end: same error.

but this still doesn't resolve the linker error.

It sounds like you only have main.cpp as the lone source file for your project -- do you have particle.cpp configured as part of the build?

[aside]

and iostream was already included in main

We can only see what you post; I don't see it in what you posted. ;)
[/aside]

Aha! I threw it into a test program and thought the #include "particle.h" would be sufficient to get the .cpp file. Thanks a ton, Dave

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.