Overloading Insertion Operator in C++

江枫思渺然 提交于 2019-12-23 19:11:22

问题


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:


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;
}



回答2:


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;
}



回答3:


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;
}



回答4:


I found this helpful!

My insertion and extraction operators are slightly different.

here they are defined:

friend ostream& operator<<(ostream &fout, datatype toPrint)

friend istream& operator>>(istream &fin, datatype &toReadTo)

the syntax needs to be exact.



来源:https://stackoverflow.com/questions/1712394/overloading-insertion-operator-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!