gpt4 book ai didi

c++ - 不匹配运算符<<

转载 作者:太空宇宙 更新时间:2023-11-04 13:04:22 25 4
gpt4 key购买 nike

我正在尝试编写一个带有重载的类 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;
}

关于c++ - 不匹配运算符<<,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43053957/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com