I’m newbie in c++, got unexpected error while <<operator Overloading. Could you tell me some advise?

  c++, operator-overloading

While doing some code practice myself I got some Error

student.h file

#pragma once
class Student {

public:
    Student() = default;
    Student(int id, const char* name, int score);
    Student(const Student& s);
    
    Student(Student&& other);
    Student& operator=(Student&& other);
    virtual ~Student();

    **friend std::ostream & operator<<(std::ostream & os, const Student & rhs);**

    void print();
private:
    int mId;
    char* mName;
    int mScore;
    size_t mSize;
};

student.cpp file

#include "student.h"
#include <iostream>
#include <string>


... //bunch of constructors, override...

    std::ostream & operator<<(std::ostream& os, const Student & rhs)
    {
        os << rhs.mId << rhs.mName << rhs.mScore ; // Compile Error: Cannot Access Student Member(rhs.mId, rhs.mName...)
    
        return os;
    }

The Error i got was i cannot access Student class member despite I declared it friend function in student.h

Strange to me, It compiled successfully if i declare #include<iostream> statement in student.cpp file like this

#include <iostream>     //change position <iostream> and "student.h"
#include <string>

#include "student.h"


... //bunch of constructors, override...

    std::ostream & operator<<(std::ostream& os, const Student & rhs)
    {
        os << rhs.mId << rhs.mName << rhs.mScore ; //Compile successfully
    
        return os;
    }

So, why #include statement sequences are matters? i thought #include statement just copy-paste to my cpp file.

And it also compiled successfully when i declare #include<iostream> to student.h,

so when i include some #include things the Best-case is declare it to header-file?

Could you give me some advise?

I compiled my program in Visual Studio 2019.

Source: Windows Questions C++

LEAVE A COMMENT