c++重载的友元函数无法访问私有(private)成员

标签 c++ c++11

目前正在做一个项目,我的教授要求我们重载流提取和输入运算符。我复制了他给我们的标题以开始我的实现。这是我的标题 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/

相关文章:

c++ - 动态链接时,应用程序如何知道要加载哪个 DLL 文件?

c++ - 在第三方应用程序中操作滚动条

c++ - if(null) 正在使用 clang++ 编译的特定计算机中执行

c++ - 禁用 move 构造函数

c++ - std::forward 实现之间的区别

c++ - 文件映射对象和文件对象可以互换使用吗?

c++ - QDialog show() 跟随返回结果 Action

c++ - 将 std::unique_ptr.get() 作为参数传递给 addWidget()

c++ - fetch_sub 和 memory_order_relaxed 用于原子引用计数?

c++ - 用于基于任务的并行性的通用 c++11 函数包装器