简体   繁体   中英

C++ operator overload doesnt work

I have a question about operators and how to overload them. There is an example of code and I'm overloading operator<< but it doesn't work. There is class that I use:

class CStudent{ //class for students and their attributes
    int m_id;
    int m_age;
    float m_studyAverage;

    public:

    CStudent(int initId, int initAge, float initStudyAverage): m_id(initId), m_age(initAge), m_studyAverage(initStudyAverage){}

    int changeId(int newId){
        m_id = newId;
        return m_id;
    }
    int increaseAge(){
        m_age++;
        return m_age;
    }
    float changeStudyAverage(float value){
        m_studyAverage += value;
        return m_studyAverage;
    }
    void printDetails(){
        cout << m_id << endl;
        cout << m_age << endl;
        cout << m_studyAverage << endl;
    }

    friend ostream operator<< (ostream stream, const CStudent student);
};

Overload:

ostream operator<< (ostream stream, const CStudent student){
    stream << student.m_id << endl;
    stream << student.m_age << endl;
    stream << student.m_studyAverage << endl;
    return stream;
}

And there is main method:

int main(){

    CStudent peter(1564212,20,1.1);
    CStudent carl(154624,24,2.6);

    cout << "Before the change" << endl;
    peter.printDetails();
    cout << carl;

    peter.increaseAge(); 
    peter.changeStudyAverage(0.3);
    carl.changeId(221783);
    carl.changeStudyAverage(-1.1);

    cout << "After the change" << endl;
    peter.printDetails();
    cout << carl;

    return 0;
}

Where is the problem?

这里的问题是你需要了解什么引用和std :: ostream和std :: ostream&之间的区别。

std::ostream& operator<< (std::ostream& stream, const CStudent& student)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM