【问题标题】:C++ operator overload doesnt workC++ 运算符重载不起作用
【发布时间】:2013-05-12 00:44:54
【问题描述】:

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

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

还有main方法:

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

问题出在哪里?

【问题讨论】:

  • 什么不起作用?是否有编译器错误消息或运行时错误?
  • operatorfriend std::ostream & operator<<(std::ostream & stream, CStudent const & student)
  • @pmr 有一个错误我无法编译它
  • @TomKnapen 谢谢它,解决了问题!
  • @ChrisBarlow:所以告诉我们你遇到了什么错误!不要通过隐瞒信息让帮助您变得不必要地困难。

标签: c++ operator-overloading


【解决方案1】:

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

std::ostream&amp; operator&lt;&lt; (std::ostream&amp; stream, const CStudent&amp; student)

【讨论】:

  • 谢谢你,就是这样,不知道我怎么错过了
猜你喜欢
  • 2013-06-17
  • 1970-01-01
  • 1970-01-01
  • 2021-05-22
  • 1970-01-01
  • 2014-05-16
  • 1970-01-01
  • 1970-01-01
  • 2015-05-25
相关资源
最近更新 更多