2013-05-12 76 views
0

我有一个关于运算符的问题,以及如何重载它们。有一个代码示例,我超载operator<<但它不起作用。还有的是,我使用类:C++运算符重载不起作用

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); 
}; 

过载:

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

而且有主要方法:

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; 
} 

问题出在哪里?

+1

什么不行?是否有编译器错误消息或运行时错误? – pmr 2013-05-12 00:48:00

+1

operator <<因为它的第一个参数应该引用一个ostream(std :: ostream&),并且它也应该接受一个const引用(CStudent const&),因为它是第二个参数。最后但并非最不重要的是,它应该返回对传入的ostream的引用。所以总结一下:'朋友std :: ostream&operator <<(std :: ostream&stream,CStudent const&student)' – 2013-05-12 00:48:41

+1

@pmr有一个错误,我不能编译它 – 2013-05-12 00:51:36

回答

2

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

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

+0

谢谢你,不知道我是如何错过它的 – 2013-05-12 00:53:45