C++ 运算符重载不起作用

标签 c++ operator-overloading

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

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

问题出在哪里?

最佳答案

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

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

关于C++ 运算符重载不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16503104/

相关文章:

c++ - nuget 包管理器包含在 VS 2015 中设置的目录在哪里?

Linux 下 C++ 编译错误

c# - 编写一个不是容器的泛型类? [C#]

c++ - 为类中的自定义类型重载 operator=

c++ - 模板中默认类型的重载运算符

C++ 二进制文件读入结构

c++ - 十进制到二进制转换器 C++?

c++ - 在绕过 stdafx.h 依赖项的同时在项目之间共享类

c++ - 在 C++ 中预定义 >> 运算符以跳过 '(' 和 ')'

c++ - operator>> 重载的显式实例化