目前正在做一个项目,我的教授要求我们让流提取和输入运算符过载。我已经复制了他提供给我们的标头以开始实施。这是我的负责人Student.h:

// @file student.h
#ifndef STUDENT_H
#define STUDENT_H
#include <string>
using namespace std;
class Student {
    /** add all the setter and getter methods **/
    /**
   * @param is the input stream
   * @param course the student object reference
   * @return the input stream
   */
    friend istream &operator >> (istream &is, Student &student);
    /**
   * @param os the output stream
   * @param course the student object reference
   * @return the output stream
   */
    friend ostream& Student::operator << (ostream& os, const Student& student);

public:
    Student();
    Student(string firstName, string lastName, int id, char grade);

    void setFirstName(string firstName);
    string getFirstName();


private:
    string firstName;
    string lastName;
    int id;
    char grade;
};
#endif /* STUDENT_H */


这是我使用文件Student.cpp的定义

#include "student.h"
#include <iostream>
using namespace std;


istream &operator >> (istream &is, Student &student) {
    is >> student.firstName;
}


CLion不断告诉我firstName是私有的,因此无法访问,我是否有明显的遗漏?我已经检查并仔细检查了格式,并多次移动了“&”号,但很难知道它是什么。

是的,我已经看过一个类似标题的问题,他在使用的名称空间遇到问题,尝试过但没有结果。任何帮助是极大的赞赏。

最佳答案

我无法解释错误消息,但是该函数必须返回一个值。

istream &operator >> (istream &is, Student &student) {
    return (is >> student.firstName);
}


修复该问题以及缺少的构造函数等,以及main(),它应该可以正常编译。

P.s.将类Student放在属于您,属于您的名称空间中,并且永远不要在头文件中写入using namespace std;

09-10 00:42
查看更多