目前正在做一个项目,我的教授要求我们重载流提取和输入运算符。我复制了他给我们的标题以开始我的实现。这是我的标题 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 是私有(private)的,因此无法访问,有什么明显的我遗漏的吗?我检查并仔细检查了我的格式,并将符号移动了很多,但我很难说出它是什么。
是的,我已经查看了他在使用的命名空间方面遇到问题的同名问题,尝试过但没有看到任何结果。非常感谢任何帮助。
最佳答案
我无法解释错误消息,但该函数必须返回一个值。
istream &operator >> (istream &is, Student &student) {
return (is >> student.firstName);
}
修复它和缺少的构造函数等,以及 main()
,它应该可以正常编译。
附言将 Student 类放在一个完全属于您的命名空间中,永远不要在头文件中编写using namespace std;
。
关于c++重载的友元函数无法访问私有(private)成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48634078/