C2679:二进制"<<":未找到采用类型为"student"的右操作数的运算符(或没有可接受的转换)

C2679: binary '<<' : no operator found which takes a right-hand operand of type 'student' (or there is no acceptable conversion)

本文关键字:lt 运算符 操作数 转换 可接受 类型 二进制 C2679 student      更新时间:2023-10-16

我真的不知道为什么我会收到错误,但话又说回来,我不太擅长这个,现在我只是想弄清楚为什么我无法打印出我的记录数组。认为有人能为我指出正确的方向吗?它还没有接近完成,所以它有点粗糙...

#include <iostream>
#include <fstream>
#include <string> 

using namespace std;
class student
{
private:
    int id, grade;
    string firstname, lastname;
public:
    student();
    student(int sid, string firstn, string lastn, int sgrade);
    void print(student* records, int size);
};
void main()
{
    string report="records.txt";
    int numr=0 , sid = 0,sgrade = 0;
    string firstn,lastn;
    student *records=new student[7];
    student stu;
    student();
    ifstream in;
    ofstream out;
    in.open(report);
    in>>numr;
    for(int i=0; i>7; i++)
    {
        in>>sid>>firstn>>lastn>>sgrade;
        records[i]=student(sid, firstn,lastn,sgrade);
    }
    in.close();
    stu.print(records, numr);
    system("pause");
}
student::student()
{
}
student::student(int sid, string firstn, string lastn, int sgrade)
{
    id=sid;
    firstname=firstn;
    lastname=lastn;
    grade=sgrade;
}
void student::print(student* records, int size)
{
    for(int i=0; i>7; i++)
        cout<<records[i]<< endl;
}

与Java等语言不同,C++不提供默认的打印方式。为了使用cout您必须执行以下 2 项操作中的 1 项:

  1. 提供对可打印内容的隐式转换(不要这样做)
  2. 重载<<运算符,如下所示:

    ostream& operator <<(ostream& str, const student& printable){
        //Do stuff using the printable student and str to print and format
        //various pieces of the student object
        return str;
        //return the stream to allow chaining, str << obj1 << obj2
    }