views:

807

answers:

3

I have a class in which I'm trying to overload the << operator. For some reason, it is not being overloaded.

Here is my .h file:

friend std::ostream& operator<<(std::ostream&, const course &); //course is my class object name

in my .cpp, I have this as my implementation:

std::ostream& operator<<(std::ostream &out, const course & rhs){
    out << rhs.info;
    return out;
}

This should be correct, but when I try to compile it, it says that cout << tmp; is not defined in ostream.

I've included iostream in my .cpp and .h

I'm been pulling my hair out trying to figure this out. Can you see anything that's wrong with this?

EDIT: Since what I'm doing seems to be correct, here's all of my source code: http://pastebin.com/f5b523770

line 46 is my prototype

line 377 is the implementation

line 435 is where it fails when i attempt to compile it.

also, I just tried compiling it on another machine, and it gives this error instead:

course.cpp:246: error: non-member function 'std::ostream& operator<<(std::ostream&, const course&)' cannot have cv-qualifier
make: *** [course.o] Error 1
+1  A: 

You should include the rest of the code, I don't think we can see where the problem is.

The following trivial example works:

class course
{
public:
    course(int info) : info(info) { }
    int info;

    friend std::ostream& operator<<(std::ostream&, const course &);
};

std::ostream& operator<<(std::ostream &out, const course & rhs)
{
    out << rhs.info;
    return out;
}

int main(int, char*[])
{
    course tmp(3);
    std::cout << tmp;
    return 0;
}
Tim Sylvester
+2  A: 

The syntax you've listed is correct, but the overloaded operator prototype has to be declared in the course definition to work properly.

course.h

class course {
public:
  friend std::ostream& operator<<(std::ostream&, const course&);
private:
  int info;
}

course.cpp

std::ostream& operator<<(std::ostream &out, const course &rhs){
  out << rhs.info;
  return out;
}
goldPseudo
+1  A: 

It looks fine to me. Here's my version of it:

course.h

#include <iostream>

class course
{
public:
    friend std::ostream& operator<<(std::ostream&, const course &); //course is my class object name
    int info;
    course(){info = 10;}
};

course.cpp

#include <iostream>    
#include "course.h"

std::ostream& operator<<(std::ostream &out, const course & rhs)
{
    out << rhs.info;
    return out;
}

main_file.cpp

#include <iostream>
#include "course.h"

int main()
{
    course a;
    std::cout<<a;

    return 0;
}
Jacob