Domanda

My current code is not working. I am trying to use << operator of Person class in the << operator of Student class. Is that possible?

#include <iostream>
using namespace std;

class Person
{   
private:
int EGN;
public:
Person(int e):EGN(e){}
friend ostream& operator <<(ostream& out, const Person& p);
};
ostream& operator <<(ostream& out, const Person& p)
{
    out<<p.EGN<<endl;
    return out; 
}

class Student: public Person
{   
    private:
    int fn;
    public:

Student(int e, int f):Person(e)
{

    fn=f;

}
friend ostream& operator <<(ostream& out, const Student& p);
};

 ostream& operator <<(ostream& out, const Student& p)
{
    Person :: operator << (out,p);
    out<<p.fn<<endl;
    return out; 
}
È stato utile?

Soluzione

Person's operator << is a friend, not a member, so you can't access it using the :: operator.

Try casting your student to a person to call the right overload:

out << static_cast<const Person &>(p);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top