1

Suppose this is my class:

class Student {
    std::string name;
    int CWID;
public:
    Student(std::string name = "N/A", int CWID = 99999999) : this->name(name), this->CWID(CWID) {}
};

Now, how do I overload the output stream operator << that will print all the data in the class. I'm guessing this is equivalent to the toString() method in Java but kindly show me how to do it in C++.

Blood Brother
  • 105
  • 1
  • 2
  • 7
  • This has been asked many times, what about the previous answers to similar questions did not help you? – Borgleader Apr 08 '15 at 18:00
  • possible duplicate of [Operator overloading](http://stackoverflow.com/questions/4421706/operator-overloading) – AChampion Apr 08 '15 at 20:20

3 Answers3

1

Add member functions to the class that return the name and CWID.

std::string getName() const {return name;}
int getCWID() const {return CWID;}

Then, add a non-member function to write the data out to a stream.

std::ostream& operator<<(std::ostream& out, Student const& s)
{
   return out << s.getName() << " " << s.getCWID();
}
R Sahu
  • 204,454
  • 14
  • 159
  • 270
0

You could write non-member function

std::ostream& operator<<(std::ostream& os, const Student& stud)
{
  os << stud.name << " " << stud.CWID;
  return os;
}

and declare it as friend function in your class

class Student {
    std::string name;
    int CWID;
public:
    Student(std::string name = "N/A", int CWID = 99999999) : this->name(name), this->CWID(CWID) {}
    friend ostream& operator<<(ostream& os, const Student& stud);
};
kvorobiev
  • 5,012
  • 4
  • 29
  • 35
0

Here is how you do it:

class Student {
    std::string name;
    int CWID;
public:
    Student(std::string name = "N/A", int CWID = 99999999) : name(name), CWID(CWID) {}

    friend std::ostream& operator<<(std::ostream& stream, const Student& student);
};


std::ostream& operator<<(std::ostream& stream, const Student& student)
{
    stream << '(' << student.name << ", " << student.CWID << ')';
    return stream;
}

Please note that this overloaded function is not part of the class.

kamshi
  • 605
  • 6
  • 19