不匹配运营商<<

时间:2017-03-27 18:33:05

标签: c++ operator-overloading

我正在尝试编写一个重载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,但没有任何更改。

提前谢谢。

1 个答案:

答案 0 :(得分:0)

以下是如何使磁通量运算符过载的示例:

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