Boris N February 2016

Implementing the extraction and insertion operator C++

I have a basic Student class (has to be a class)(yes there is no encapsulation and also namespace pollution pls forgive) and I would like to create custom extraction and insertion operators. After countless searches it still would not work. What I have is this

#ifndef student
#define student

#include <iostream>
#include <string>

using namespace std;

class Student
{
    public:
        string name;
        double score;

        Student();
        Student(string name, double score) : name(name), score(score) {}

        friend ostream& operator<<(ostream &out, Student &student);
        friend istream& operator>>(istream &in, Student &student);
};

#endif

#include "student.h"

ostream& operator<<(ostream &out, Student &student)
{
    out << student.name << ", " << student.score;
    return out;
}

istream& operator>>(istream &in, Student &student)
{
    if (!in >> name || !in >> score)
    {
        in.setstate(ios::failbit);
    }
    return in;
}

I have tried many things from this->name to Student::name to name to Student::student.name to changing the function signature that actually did end up working except it did not actually overload the operator. pls halp :D

Edit: As for the specific problem, it is acessing the member of the Student class within the method. student.name and student.score are throwing an

expected primary-expression before '.' token

and the bottom one is simply a relic of throwing different solution at it but it's scope error.

Edit2: The problem turn out to be a conflict with the guard in the header being called student thus the pre-processor would nuke the word student everywhere -_- Thanks for the help

Answers


Captain Giraffe February 2016

I see a few problems with your >>

if (!in >> name || !in >> score)

! has higher priority than >>, use !(in >> student.name)

use student.name and student.score

Just as you did in the previous operator.

It is useful to use a const reference to the second argument for the << operator. Change the friend declaration accordingly.


mindriot February 2016

Various problems have been pointed out in the comments and in Captain Giraffe's answer. Another more critical problem is this:

You declare a variable called student in your functions; but your header actually #defines student in the header guard! So your #defined symbol clashes with your variable name, resulting in the errors you see. A recommended syntax for the header guard is something like

#define STUDENT_H_INCLUDED

Post Status

Asked in February 2016
Viewed 1,204 times
Voted 12
Answered 2 times

Search




Leave an answer