c++extractinsertionextraction-operator

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


Solution

  • 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