操作员不匹配<<

No match for operator<<

本文关键字:lt 不匹配 操作员      更新时间:2023-10-16

我正在尝试编写一个带有重载operator<<的类,但它一直给我这个错误。这是我的代码:

//Course.h
friend ostream& operator<<(ostream& os,Course& course);
//Course.cpp
ostream& operator<<(ostream& os,Course& course)
{
os << course.courseCode << " " << course.credit << " " << course.section " " << endl;
return os;
}

这是所有的 .h

#ifndef COURSE_H
#define COURSE_H
#include <string>
using namespace std;
class Course
{
    public:
        Course();
        Course(string code,int credit,int section);
        virtual ~Course();
        string getCourseCode();
        void setCourseCode(string code);
        int getCredit();
        void setCredit(int credit);
        int getSection();
        void setSection(int section);
        bool operator==(Course &course);
        bool operator!=(Course &course);
        friend ostream& operator<<(ostream& os,const Course& course);
    private:
        string courseCode;
        int credit,section;
};
#endif // COURSE_H

这是.cpp的一部分

#include "Course.h"
.
.
//Other functions' implementations
ostream& operator<<(ostream& os,const Course& course)
{
    os << course.courseCode << " " << course.credit << " " << course.section " " << endl;
}

我更改了参数const但没有任何变化。

提前谢谢你。

下面是有关如何重载通量运算符的示例:

#include <iostream>
class Test
{
public:
    Test(int a, int b) : a(a), b(b) {}
    friend std::ostream& operator<<(std::ostream& stream, const Test& t);
private:
    int a;
    int b;
};
std::ostream& operator<<(std::ostream& stream, const Test& t)
{
    stream << "Test::a " << t.a << "nTest::b " << t.b << 'n';
    return stream;
}
int main()
{
    Test t(20, 40);
    std::cout << t;
    return 0;
}